Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Created June 21, 2015 22:31
Show Gist options
  • Save postpostscript/75fc20ad7ee46aefd595 to your computer and use it in GitHub Desktop.
Save postpostscript/75fc20ad7ee46aefd595 to your computer and use it in GitHub Desktop.
Simple event triggering/handling framework
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;
};
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