Created
May 15, 2012 21:40
-
-
Save johnhunter/2705360 to your computer and use it in GitHub Desktop.
An observable decorator
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
/** | |
* Creates or decorates an object with observable behavior. | |
* @param {[type]} o object to decorate | |
* @return {[type]} the observable object | |
*/ | |
function makeObservable (o) { | |
var undef; | |
o = o || {}; | |
if (o.subscribers) { | |
throw('Object is already an Observable'); | |
} | |
o.subscribers = { any: [] }; | |
o.subscribe = function (fn, type) { | |
type = type || 'any'; | |
if (o.subscribers[type] === undef) { | |
o.subscribers[type] = []; | |
} | |
o.subscribers[type].push(fn); | |
}; | |
o.unsubscribe = function (fn, type) { | |
var subscribers = o.subscribers[type || 'any'], | |
i = subscribers.length; | |
while (i--) { | |
if (subscribers[i] === fn) { | |
subscribers.splice(i, 1); | |
} | |
} | |
}; | |
o.publish = function (message, type) { | |
var subscribers = o.subscribers[type || 'any'], | |
i = subscribers.length; | |
while (i--) { | |
if (subscribers[i] === fn) { | |
subscribers[i](message); | |
} | |
} | |
}; | |
return o; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment