Skip to content

Instantly share code, notes, and snippets.

@shakesoda
Created October 21, 2011 20:52
Show Gist options
  • Save shakesoda/1304926 to your computer and use it in GitHub Desktop.
Save shakesoda/1304926 to your computer and use it in GitHub Desktop.
JavaScript: This is what I get for not wanting to repeat myself.
/*
* 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