Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I want to add some functions inside a existent class in OpenLayers. For example, I want to add function A() and B() and a variable C inside OpenLayers.Layer.Vector.

var X = function() {
    A() = funtion { /* something */ },

    B() = funtion { /* something */ },

    C = 'something'

}

So when I create a new layer inside a map object I could call those function by:

map.layer[1].A();

or could change:

map.layer[1].C = 'something else';

I tried many ways but didn't worked well. And most of the time, when I tried to change the C var inside one layer it changed the other too.

share|improve this question

2 Answers 2

You have two options:

  1. add a method or property to an instance (this vector layer object only)
  2. add a method or property to the vector prototype (all vector layers, even already existing ones)

Option 1:

map.layer[1].A = function() {

};
map.layer[1].B = function() {
    
};
map.layer[1].C = 'something';

//later...

map.layer[1].A();
map.layer[1].B();
map.layer[1].C = 'something else';

OR:

var X = function() {
    A() = funtion { /* something */ },

    B() = funtion { /* something */ },

    C = 'something'
};
map.layer[1].myX = X; //<-- Augment OpenLayers Vector Class with X.

map.layer[1].myX.A();

map.layer[1].myX.B();

map.layer[1].myX.C = "Something Else";

Option 2:

You could augment it's prototype like so:

OpenLayers.Layer.Vector.prototype.A = function () {
    alert(this.CLASS_NAME);
};
map.layer[1].A();

One was is NOT better than the Other. It just depends on what you want to do.

share|improve this answer

Look at applyDefaults where you would define a 'from' object:

var from = {
    A: function() {},
    B: function() {},
    C: "hello"
};

var layer1 = OpenLayers.Util.applyDefaults(map.layer[1], from);

This should give you a unique A,B,C value on each to object. It's probably not what you really want to do. You probably really want C to be unique and use a single instance of A and B. If that's the case look into OpenLayers.Util.extend for A and B and then simply set to.C = "value".

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.