Created
June 21, 2015 22:31
-
-
Save postpostscript/75fc20ad7ee46aefd595 to your computer and use it in GitHub Desktop.
Simple event triggering/handling framework
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
function hasProperty(obj, prop) { | |
return obj[prop] !== undefined; | |
}; | |
Array.prototype.callFunction = function(target, key) { | |
var args = [].splice.call(arguments, 0).slice(2); | |
this.forEach(function(elem) { | |
try { | |
if (hasProperty(elem, key) && typeof elem[key] == 'function') { | |
elem[key].apply(target, args); | |
} else if (!key && typeof elem == 'function') { | |
elem.apply(target, args); | |
} | |
} | |
catch(e) {} | |
}); | |
}; | |
obj.on = function(key, handler) { | |
this.eventListeners = (this.eventListeners || {}); | |
this.eventListeners[key] = (this.eventListeners[key]||[]); | |
this.eventListeners[key].push(handler); | |
return this; | |
} | |
obj.trigger = function(key, data) { | |
this.eventListeners = (this.eventListeners || {}); | |
var listeners = (this.eventListeners[key] || []); | |
listeners.callFunction(this, '', data); | |
return this; | |
} | |
obj.off = function(key) { | |
this.eventListeners[key] = []; | |
return this; | |
}; |
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
obj.on('example-event', function(data) { | |
console.log('received example-event with data: ' + JSON.stringify(data)) | |
}); | |
obj.trigger('example-event', { | |
// Data is here | |
exampleData: 2, | |
moreData: 3 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment