Created
May 29, 2011 04:25
-
-
Save pec1985/997465 to your computer and use it in GitHub Desktop.
Custom Event in browser JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tested only in safari. Use at your own risk. | |
Element.prototype.fireEvent = function(a,b) { | |
b = b || {}; | |
b.type = a; | |
b.source = this; | |
var evt = document.createEvent("Events"); | |
evt.initEvent(a, true, true); | |
for(var i in b){ | |
if(b){ evt[i] = b[i]; } | |
} | |
evt.value = b; | |
this.dispatchEvent(evt); | |
}; | |
//======== Example ========= | |
var btn = document.createElement('button'); | |
btn.addEventListener('pedro', function(e){ | |
alert(e.hello); // alerts "world" | |
}); | |
btn.addEventListener('click', function(){ | |
btn.fireEvent('pedro', { hello: 'world' }); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment