Created
April 29, 2015 05:07
-
-
Save jmas/1653578572d96b60ddd5 to your computer and use it in GitHub Desktop.
Tiny javascript observable
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
function observable(obj) { | |
var listeners = {}; | |
// | |
obj.on = function(name, handler) { | |
if (! (name in listeners)) { | |
listeners[name] = []; | |
} | |
listeners[name].push(handler); | |
return this; | |
}; | |
// | |
obj.off = function(name, handler) { | |
if (! handler && name in listeners) { | |
delete listeners[name]; | |
return this; | |
} | |
for (var i=0,ln=listeners[name].length; i<ln; i++) { | |
if (listeners[name][i] === handler) { | |
listeners[name][i].splice(i, 1); | |
} | |
} | |
return this; | |
}; | |
// | |
obj.trigger = function(name, params) { | |
if (! (name in listeners)) { | |
return this; | |
} | |
for (var i=0,ln=listeners[name].length; i<ln; i++) { | |
listeners[name][i].apply(obj, params); | |
} | |
return this; | |
}; | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment