Event Emitter

Simple Event Emitter

// simple Emitter, without storing emitted events that weren't handled
//
// usage example:
// var myEmitter = new Emitter()
// myEmitter.on('420', function(data) {
// 	console.log(this.type, data)
// })
// myEmitter.emit('420', 'blaze it')
function Emitter() {
	this.listeners = {}
}
Emitter.prototype = {
	on: function(type, method) {
		var arr = this.listeners[type]
		if(arr == undefined) {
			arr = []
			this.listeners[type] = arr
		}
		arr.push(method)
	},
	emit: function(type, obj) {
		var arr = this.listeners[type]
		if(arr == undefined) {
			return
		}
		for(var i = 0; i < arr.length; i++) {
			arr[i].call({type: type}, obj)
		}
	}
}

// example code
var gEmitter = new Emitter()

gEmitter.on('something-happened', function(data) {
	console.log(data)
})
gEmitter.emit('something-happened', 'A door opened somewhere')