Skip to content

Instantly share code, notes, and snippets.

@rikkiloades
Created March 5, 2013 11:19
Show Gist options
  • Save rikkiloades/5089640 to your computer and use it in GitHub Desktop.
Save rikkiloades/5089640 to your computer and use it in GitHub Desktop.
Very simple JavaScript events system.
var Events = {
/**
* Given a object will mix the ability to emit events into the object
* and listen for those events from other functions. Gives the destObject
* the following three additional methods: on, off, emit.
*
* @param {Object} destObject
*/
mixin: function(destObject) {
var methods = {
on: function(event, callback) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(callback);
},
off: function(event, callback) {
this._listeners = this._listeners || {};
if (event in this._listeners === false) return;
this._listeners[event].splice(this._listeners[event].indexOf(callback), 1);
},
emit: function(event) {
this._listeners = this._listeners || {};
if (event in this._listeners === false) return;
for (var i = 0; i < this._listeners[event].length; i++) {
this._listeners[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
};
for(var methodName in methods) {
if (methods.hasOwnProperty(methodName)) {
destObject.prototype[methodName] = methods[methodName];
}
}
},
/**
* Creates a object with the ability to emit events and
* be listened too.
*
* @return {Object}
*/
create: function() {
var newObj = {};
this.mixin(newObj);
return newObj;
}
};
// centralised notification center
var notificationCenter = Events.create();
notificationCenter.on('message', function(message) {
console.log('MESSAGE RECIEVED: ' + message);
});
notificationCenter.emit('message', 'hello world');
// mixing events into an existing object
var app = {
boot: function() {
// do somthing
this.emit('ready');
}
};
Events.mixin(app);
app.on('ready', function() {
console.log('App booted and ready!');
});
app.boot();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment