Prototype property not defined inside OL3 custom control constructor

I am trying to create a custom control in ol3. I met this example and decided to make some kind of class instead of one big heap of code on the whole page. So, I have something like this:

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 _triggerit is not being called. One way to do this is to place it _triggerinside the constructor:

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

But I don’t like it, because the code in one heap again and all OOP crashes.

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

+4
source share
1

inherits prototype .

_triggered inherits, :

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!");
};
+2

Source: https://habr.com/ru/post/1627987/


All Articles