JavaScript event callback function scope issue with this? -
i having bit of trouble understanding concept. have loop in assign events , handlers elements. problem within callback, accessing member function. set scope correct this
(referring object) e.target
, not getting correct element. guess want correct element. below code.
for(var in type) { element.addeventlistener(type[i].tolowercase(), (function (_self, handler) { //handle reference in event callback //using closure return callback correct context return function (event) { //console.log(arguments); //console.log(this); _self[handler].apply(_self, arguments); } }(this, type[i])), capture); }
now within handler function:
dragstart: function (e) { console.log(e); var = e.target, sectionname = that.id, interactiontarget = that.childnodes[0].alt; e.datatransfer.effectallowed = 'move'; e.datatransfer.setdata('text/html', that.innerhtml); this.dragsrcel = that; that.classlist.add('fade'); this.triggerevent("whatever"); },
triggerevent
member function. want correct this
corresponding object , correct element event bound.
i think understand asking now. here's how might it:
for(var in type) { element.addeventlistener( type[i].tolowercase(), this[type[i]].call(this, element), capture) }
and dragstart: (if using es5)
dragstart: function (element) { return function(e){ //this === original object //element === listening element //e.target === firing element }.bind(this) }
if older ie needs supported:
dragstart: function (element) { var self = return function(e){ //self === original object //element === listening element //e.target === firing element } }
Comments
Post a Comment