Search code examples
javascriptclientopenlayers

How to access function in click handler function?


I create this class using pure javascript:

var SelectFeature = /*@__PURE__*/(function (Select) {
    function SelectFeature() {
        Select.call(this, {
            condition: ol.events.condition.click
        });
    }

    this.on('select', function (e) {
        //some logic
    });

    if (Select) SelectFeature.__proto__ = Select;
    SelectFeature.prototype = Object.create(Select && Select.prototype);
    SelectFeature.prototype.constructor = Select;

    return SelectFeature;
}(ol.interaction.Select));

as you can see I pass ol.interaction.Select as a parameter to the class and using Select.call() the method in SelectFeature as a constructor.

Here is a description of ol.interaction.Select class.

The ol.interaction.The select class has a member who is called getFeatures(). I try to access this method when some DOM element is clicked(this block is inside SelectFeature class):

$("#popupFeat-closer").click(function () {
    this.getFeatures();
});

The code above is fired when DOM element is clicked but, on this row:

this.getFeatures();

I get this error:

Uncaught TypeError: this.getFeatures is not a function

My question how can I access getFeatures function which is located in click event handler?


Solution

  • Like it is mention in the comments, you have a context problem. Almost every library or framework has a method to keep the context, in jQuery you can achieve this with proxy method. Something like this should work,

    $("#popupFeat-closer").click($.proxy(function () {
        this.getFeatures();
    }), this);
    

    I would say that is always good to use the library/framework way of solving these, but the "old" way works too,

    var self = this;
    $("#popupFeat-closer").click(function () {
        self.getFeatures();
    });
    

    jQuery Docs - proxy