Search

9/09/2013

addEventListener, handleEvent and passing objects | The CSS Ninja - All things CSS, JavaScript & HTML

addEventListener, handleEvent and passing objects | The CSS Ninja - All things CSS, JavaScript & HTML

Here’s a super awesome trick I had no idea about until someone pointed out you could do this. addEventListener can take an object as a second argument that will look for a method called handleEvent and call it! No need for binding “this” so it will pass around the context correctly, the context is the object you’ve just set as the event listener callback.
var obj = {
    handleEvent: function() {
        alert(this.dude);
    },
    dude: "holla"
};

element.addEventListener("click", obj, false);
var obj  =  {
    init: function() {
        document.getElementById("btn").addEventListener("click", this, false);
        document.getElementById("btn").addEventListener("touchstart", this, false);
    },
    handleEvent: function(e) {
        switch(e.type) {
            case "click":
                this.button();
                break;
            case "touchstart":
                this.button();
                break;
        }
    },
    dude: "holla",
    button: function() {
        alert(this.dude);
    }
};

obj.init();
As you can see our object has an init() method which binds all the events and just passes in “this” as the callback, handleEvent then delegates off to whatever method it needs based on the event being triggered, rad.

沒有留言: