Created
January 2, 2012 16:34
-
-
Save fabrizim/1551312 to your computer and use it in GitHub Desktop.
Simple Custom Event Mixin
This file contains hidden or 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
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