Instantly share code, notes, and snippets.

Embed
What would you like to do?
EventsMixin
(function(App, Array) {
'use strict';
var slice = Array.prototype.slice;
function Events () {
var events = {};
function on (eventName, callback, context) {
if (!events[eventName]) {
events[eventName] = [];
}
events[eventName].push({ callback: callback, context: context });
}
function off (eventName) {
if (events[eventName]) {
// faster that .splice
events[eventName] = [];
}
}
function trigger (eventName) {
var args = slice.call(arguments, 1);
var registeredArr = events[eventName];
var len;
var registered;
if (registeredArr) {
len = registeredArr.length;
for(var i = 0; i < len; i++) {
registered = registeredArr[i];
registered.callback.apply(registered.context, args);
}
}
}
return function () {
this.on = on;
this.off = off;
this.trigger = trigger;
return this;
};
}
App.mixins.Events = Events;
})(App, Array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment