Skip to content

Instantly share code, notes, and snippets.

@rmcvey
Last active December 11, 2015 16:59
Show Gist options
  • Save rmcvey/4631745 to your computer and use it in GitHub Desktop.
Save rmcvey/4631745 to your computer and use it in GitHub Desktop.
Allows chaining when adding event handlers
// versatile method
Object.prototype.pushEvent = function(action, fn, bubbleStage) {
fn = fn || function(ev){};
bubbleStage = bubbleStage || false;
if('length' in this) {
for(var x = 0; x < this.length; x++){
this[x].pushEvent(action, fn, bubbleStage)
}
} else {
this.addEventListener(action, fn, bubbleStage || false);
}
return this;
}
document.querySelectorAll('a').pushEvent('click', function(e){
console.log('clicked %s', this.getAttribute('href'));
return false;
})
document.getElementById('some-id').pushEvent('click', function(e){
console.log('some-id was clicked');
});
document.querySelectorAll('.selector')
.pushEvent('click', function(ev){
console.log('clicked')
})
.pushEvent('hover', function(ev){
console.log('hovered')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment