2

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.

2 Answers 2

1

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.

1

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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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