javascript - Polymer 2.0: why do we need an anonymous function when imperatively adding listener -
in new docs polymer 2.0 (https://www.polymer-project.org/2.0/docs/devguide/events#imperative-listeners), gives following example:
ready() { super.ready(); this.addeventlistener('click', e => this._myclicklistener(e)); }
to add event listener imperatively. if wanted remove listener, have following (according docs):
constructor() { super(); this._boundlistener = this._mylocationlistener.bind(this); } connectedcallback() { super.connectedcallback(); window.addeventlistener('hashchange', this._boundlistener); } disconnectedcallback() { super.disconnectedcallback(); window.removeeventlistener('hashchange', this._boundlistener); }
this make sense me on surface; need make sure same reference function passed both remove , add event listener since that's way indexes different listeners.
however, why have use .bind(this)? understand returns new function binds function whatever "this" is, it's useful make new reference function that's saved can add , remove same function reference.
but why can't first example? doesn't this._myclicklistener(e) in first segment of code have unique function reference doesn't change can reference add , remove listener? why need wrap in anonymous function in first place? feel solve problem solved verbosely in second segment of code, it's done way reason.
thanks or suggestions in advance!
if pass this._myclicklistener
callback, wouldn't called this
value want, since dom implementation triggers call it, , not know this
: this
global object (or undefined
in strict mode).
you say, ok, bind this
this._myclicklistener.bind(this)
, don't have reference function, created on spot. when trying call removeeventlistener
cannot access this._myclicklistener.bind(this)
creates new function again, not 1 used before.
so, there no other way assign bound function variable, , use variable in both addeventlistener
, removeeventlistener
: way satisfy 2 conditions @ same time:
- you have reference function
- the function bound correct
this
Comments
Post a Comment