Skip to content

Instantly share code, notes, and snippets.

@vstarck
Created September 13, 2011 23:00
Show Gist options
  • Save vstarck/1215421 to your computer and use it in GitHub Desktop.
Save vstarck/1215421 to your computer and use it in GitHub Desktop.
Inyección de logica de eventos en objetos
/**
* Eventiza el objeto, agregandole los
* metodos
* on
* emit
* removeListener
*
* @param {Object}
* @return {Object}
*/
var eventize = (function() {
// Los metodos son unicos y se comparten
// entre todos los objetos donde se aplique
// la funcion
var on, emit, removeListener;
/**
* @param {String} event
* @param {Function} handler
* @param {Object} scope
* @return {Object}
*/
on = function(event, handler, scope) {
var handlers = this.__handlers = this.__handlers || {};
handlers[event] = handlers[event] || [];
handlers[event].push([handler, scope]);
return this;
};
/**
* @param {String} event
* @param {...mixed} arguments
* @return {Object}
*/
emit = function(event) {
var
handlers = (this.__handlers = this.__handlers || {})[event],
args = Array.prototype.slice.call(arguments, 1);
if(!handlers) {
return this;
}
for(var i = 0, l = handlers.length; i < l; i++) {
(function(fn, scope) {
fn.apply(scope, args);
})(handlers[i][0], handlers[i][1]);
}
return this;
};
/**
* @param {String} event
* @param {Function} handler
* @return {Object}
*/
removeListener = function(event, handler) {
if(!this.__handlers) {
return this;
}
if(!handler) {
delete this.__handlers[event];
return this;
}
for(var i = 0, l = this.__handlers[event].length; i < l; i++) {
if(this.__handlers[event][i][0] === handler) {
this.__handlers[event].splice(i, 1);
}
}
return this;
};
return function(obj) {
obj.on = on;
obj.emit = emit;
obj.removeListener = removeListener;
return obj;
};
})();
// Uso
var myObject = {};
// Magic!
eventize(myObject);
// attach
myObject.on('foo', console.log);
// trigger
myObject.emit('foo', 1, 2, 'bar', {a:'b'}); // 1 2 bar Object { a="b"}
// detach
myObject.removeListener('foo', console.log);
// trigger
myObject.emit('foo', 1, 2, 'bar', {a:'b'}); // ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment