Created
March 5, 2013 11:19
-
-
Save rikkiloades/5089640 to your computer and use it in GitHub Desktop.
Very simple JavaScript events system.
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
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; | |
} | |
}; |
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
// 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