There is the best sample and does not require major changes. First I will show the code.
function Bug(element) { this.focusedCell = null; // --------------------------------v----pass the object, not a function element.addEventListener('click', this, true); }; // Implement the `EventListener` interface Bug.prototype.handleEvent = function(event) { if (event.type === "click") this.onClick(event); } Bug.prototype.onClick = function(event) { console.log(JSON.stringify(this)); // '{"focusedCell":null}' console.log(event.currentTarget.nodeName); // "DIV" };
By adding the handleEvent method, we create the Bug EventListener interface. This allows us to pass a new Bug object as the second argument to addEventListener() instead of a function.
Now, when the "click" event occurs, the .handleEvent() method will be called, and the this value in this method will be the Bug object that was bound.
Since this is a reference to a Bug instance, this will obviously no longer be an element reference. But this is not necessary, since the element is available through event.currentTarget .
Of course, you can add an element directly to your Bug object in the constructor, if you want.
DEMO: http://jsfiddle.net/CnZTa/
user1106925
source share