Created
November 25, 2013 01:17
-
-
Save joeyguerra/7634798 to your computer and use it in GitHub Desktop.
Client side notification center. Publsih/Subscribe implementation in Javascript.
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(module){ | |
var observers = []; | |
module.exports.notificationcenter = { | |
publish: function(notification, publisher, info){ | |
var ubounds = observers.length; | |
var i = 0; | |
for(i; i<ubounds; i++){ | |
if(!observers[i]) continue; | |
if(observers[i].notification != notification) continue; | |
if(observers[i].publisher != null && observers[i].publisher != publisher) continue; | |
try{ | |
observers[i].observer[notification].apply(observers[i].observer, [publisher, info]); | |
}catch(e){ | |
console.log([e, observers[i]]); | |
} | |
} | |
} | |
, subscribe: function(notification, observer, publisher){ | |
observers.push({"notification": notification, "observer":observer, "publisher":publisher}); | |
} | |
, unsubscribe: function(notification, observer, publisher){ | |
var i = 0; | |
var ubounds = observers.length; | |
for(i; i<ubounds; i++){ | |
if(observers[i].observer == observer && observers[i].notification == notification){ | |
observers.splice(i, 1); | |
break; | |
} | |
} | |
} | |
}; | |
})(typeof module !== 'undefined' ? module.exports : module = {exports: {}}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var observer = {"call to action was clicked": function(publisher, info){
console.log(publisher, info);
}};
notificationcenter.subscribe("call to action was clicked", observer, null);
notificationcenter.publish('call to action was clicked', null, {"id":3, "name":"just test info"});