Created
October 21, 2011 20:52
-
-
Save shakesoda/1304926 to your computer and use it in GitHub Desktop.
JavaScript: This is what I get for not wanting to repeat myself.
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
/* | |
* Example usage: | |
* addEvents(document, { | |
* load: [ foo, bar ], | |
* click: baz | |
* }) | |
*/ | |
function addEvents(obj, list, evt) { | |
function isArray(value) { | |
return (value instanceof Array) | |
} | |
// sanity | |
if (isArray(list) && !evt) | |
alert("addEvents takes an Object, not an Array!") | |
// bind all the events in the list as needed | |
var keys = evt ? list : Object.keys(list) | |
for (i in keys) { | |
// we are recursing if evt is present. | |
var key = evt ? evt : keys[i] | |
var fn = evt ? list[i] : list[key] | |
// call ourselves while passing the key if we've got an array. | |
if (isArray(fn)) { | |
addEvents(obj, fn, key) | |
continue | |
} | |
if (obj.addEventListener) | |
obj.addEventListener(key, fn, false) | |
else if (obj.attachEvent) | |
obj.attachEvent("on"+key, fn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment