Getting access to a Polymer method inside a functi

2019-09-03 03:55发布

问题:

I use the Polymer Google Map element and I've faced with a problem while adding an event listener to the map.

    * blah blah blah *
    ready: function () {
        this.map.addEventListener('google-map-rightclick', this._rightClickOnMap);
    },
    test: function () {
        console.log(1);
    },
    _rightClickOnMap: function (event) {
        this.test();
    }
    * blah blah blah *

I've tried to bind this to the listener but JS throw me the error

this.map.addEventListener('google-map-rightclick', this._rightClickOnMap).bind(this);

回答1:

You need to call bind on the function and not on the event listener.

this.map.addEventListener('google-map-rightclick', this._rightClickOnMap.bind(this));