Skip to content

Instantly share code, notes, and snippets.

@johnhunter
Created May 15, 2012 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save johnhunter/2705360 to your computer and use it in GitHub Desktop.
Save johnhunter/2705360 to your computer and use it in GitHub Desktop.
An observable decorator
/**
* 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