Search code examples
javascriptopenlayers-3google-closure

Prototype property not defined inside a constructor of a custom OL3 control


I'm trying to create custom control in ol3. I've met this example and decided to make some class instead of one big pile of code all over the page. So I've got something like that:

var MeasureLength = function ( opt_options ) {
    var options = opt_options || {};

    var button = document.createElement( 'button' );
    button.innerText = 'M';

    button.addEventListener( 'click', this._trigger, false );

    var element = document.createElement( 'div' );
    element.className = 'measure-length ol-control';
    element.appendChild( button );

    ol.control.Control.call( this, {
        element: element,
        target: options.target
    } );
};

MeasureLength.prototype._trigger = function ( e ) {
    e.preventDefault();
    alert("Activating!");
};

ol.inherits( MeasureLength, ol.control.Control );

The problem is that _trigger is not called. One way to make it work is to place _trigger inside the constructor:

var _trigger = function ( e ) {
    e.preventDefault();
    alert("Activating!");
};
button.addEventListener( 'click', _trigger, false );

But I don't like that way because the code in one pile again and all OOP is crashing down.

So my question is: What is the best practice to create custom controls in ol3 when you have a lot of code?


Solution

  • Closure's inherits function overwrites the child's prototype by an instance of the parent.

    If you attach the _triggered attribute after calling inherits, it should be available in your child constructor:

    var MeasureLength = function ( opt_options ) {
        // should now be available
        console.log(this._trigger);
    };
    
    ol.inherits( MeasureLength, ol.control.Control );
    
    MeasureLength.prototype._trigger = function ( e ) {
        e.preventDefault();
        console.log("Activating!");
    };