javascript - "this" as object membership instead of node reference on an event handler? -
i={};i.have={};i.have.a={};i.have.a.deep={};i.have.a.deep.deep={};i.have.a.deep.deep.deep={}; i.have.a.deep.deep.deep.niceobj = { init: function(){ document.getelementbyid('xx').addeventlistener('click', this.clickhandle) }, some: function(){}, other: function(){ // here can use *this* want this.some(); }, clickhandle: function(e) { // can't use *this* want becouse *this* reffers #xx this.some() // fails!!! // here have trick, realy don't want reffer // full qualified name i.have.a.deep.deep.deep.niceobj._clickhandle(e); }, _clickhandle: function(e) { // here again *this* works want this.some(); } the question is, how can omit use of full qualified object name, inside embedded event handler, occurs in clickhandle?
you want bind function this want use.
document.getelementbyid('xx').addeventlistener('click', this.clickhandle.bind(this)); this in object function refers caller of function, when object calls function, in niceobj.init(), this niceobj. event listener calls function event target this.
so bind event listener function object instead, should this if niceobj caller of init.
https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/this
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/function/bind
Comments
Post a Comment