Gert Gert - 19 days ago 8
Javascript Question

Change behavior of a Leaflet class via include()

You can change the behavior of a Leaflet.js class by including a mixin.

The tutorial Extending Leaflet: Class Theory says:


If a class is already defined, existing properties/methods can be redefined, or new ones can be added by using .include():


However when attempting to do this, I get a
Maximum call stack size exceeded
error.



var DemoClass = L.Class.extend({
value: 42,
demoMethod: function() {
return this.value;
}
});

DemoClass.include({
demoMethod: function() {
return DemoClass.prototype.demoMethod.call(this) * 2;
},
secondMethod: function() {
return this.value;
}
});

var instance = new DemoClass();
console.log("value=" + instance.value);
console.log("secondMethod()=" + instance.secondMethod());
console.log("demoMethod()=" + instance.demoMethod()); // gives a call stack exceeded

<script src="https://unpkg.com/leaflet@1.0.1/dist/leaflet.js"></script>





If it's relevant, the actual code is overriding
L.Marker.onAdd()
.

Answer

Try to isolate the base function:

var DemoClass = L.Class.extend({
  value: 42,
  demoMethod: function() {
    return this.value;
  }
});

DemoClass.include({
  baseDemoMethod: DemoClass.prototype.demoMethod,
  demoMethod: function() {
    return this.baseDemoMethod() * 2;
  },
  secondMethod: function() {
    return this.value;
  }
});

var instance = new DemoClass();
console.log("value=" + instance.value);
console.log("secondMethod()=" + instance.secondMethod());
console.log("demoMethod()=" + instance.demoMethod());
<script src="https://unpkg.com/leaflet@1.0.1/dist/leaflet.js"></script>

Comments