Skip to content

Instantly share code, notes, and snippets.

@z2015
Last active June 7, 2016 05:11
Show Gist options
  • Save z2015/137e309c3b269a7d9faa052f00222313 to your computer and use it in GitHub Desktop.
Save z2015/137e309c3b269a7d9faa052f00222313 to your computer and use it in GitHub Desktop.
addEventListener, handleEvent and passing objects

Addeventlistener passed obj with handleevent to fn

  var obj = {
    handleEvent: function() {
        alert(this.dude);
    },
    dude: "holla"
  };

  element.addEventListener("click", obj, false);

Example 1

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();

Example 2

changeHandleEvent: function(evt) {
    this._handleEvent = this.handleEvent;
    // Change the the handleEvent method without needing to remove 
    // and re-attach the event(s)
    this.handleEvent = function(e) {
        var t = evt.target;
        
        if (t.id === "btn") {
            // Check the button being clicked and do new stuff
        } else if(t.id === "btn3") {
            this.revertHandleEvent();
        }
    }
}

Polyfill handleevent

// fn arg can be an object or a function, thanks to handleEvent
function on(el, evt, fn, bubble) {
    if("addEventListener" in el) {
        // BBOS6 doesn't support handleEvent, catch and polyfill
        try {
            el.addEventListener(evt, fn, bubble);
        } catch(e) {
            if(typeof fn == "object" && fn.handleEvent) {
                el.addEventListener(evt, function(e){
                    // Bind fn as this and set first arg as event object
                    fn.handleEvent.call(fn,e);
                }, bubble);
            } else {
                throw e;
            }
        }
    } else if("attachEvent" in el) {
        // check if the callback is an object and contains handleEvent
        if(typeof fn == "object" && fn.handleEvent) {
            el.attachEvent("on" + evt, function(){
                // Bind fn as this
                fn.handleEvent.call(fn);
            });      
        } else {
            el.attachEvent("on" + evt, fn);
        }
    }
}

source: https://www.thecssninja.com/javascript/handleevent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment