Skip to content

Instantly share code, notes, and snippets.

@fabrizim
Created January 2, 2012 16:34
Show Gist options
  • Save fabrizim/1551312 to your computer and use it in GitHub Desktop.
Save fabrizim/1551312 to your computer and use it in GitHub Desktop.
Simple Custom Event Mixin
function EventMixin(Target){
var listeners = {};
var methods = {
emit : function(ev){
if( !listeners[ev] ) return;
var ar = listeners[ev];
var args = [].slice.call(arguments, 1);
for(var i=0; i<ar.length; i++) ar[i].apply(this, args);
},
on : function(ev, fn){
if( !listeners[ev] ) listeners[ev] = [];
var ar = listeners[ev];
for(var i=0; i<ar.length; i++) if( ar[i] == fn ) return;
listeners[ev].push(fn);
},
un : function(ev, fn){
if( !listeners[ev] ) return;
var ar = listeners[ev];
for(var i=0; i<ar.length; i++) if( ar[i] == fn ){
ar.splice(i,1);
return;
}
}
};
for(var name in methods)
if( methods.hasOwnProperty(name) )
Target.prototype[name] = methods[name];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment