singleton NotificationCenter

This commit is contained in:
Jeena Paradies 2012-07-22 02:19:28 +02:00
parent b8e6a967ee
commit 55505106e4

41
app/Game/Server/NotificationCenter.js Executable file → Normal file
View file

@ -1,30 +1,32 @@
define( define(function() {
var NotificationCenter = { function NotificationCenter() {
topics: {}, this.topics = {};
subUid: -1 this.subUid = -1;
}; }
NotificationCenter.trigger = function(topic, args) { NotificationCenter.prototype.trigger = function(topic, args) {
if (!NotificationCenter.topics[topic]) { if (!this.topics[topic]) {
throw "No such topic " + topic + ". Could not trigger."; throw "No such topic " + topic + ". Could not trigger.";
} }
var subscribers = NotificationCenter.topics[topic]; var subscribers = this.topics[topic];
var len = subscribers ? subscribers.length : 0; var len = subscribers ? subscribers.length : 0;
while (len--) { while (len--) {
subscribers[len].func(topic, args); subscribers[len].func(topic, args);
} }
return this;
} }
NotificationCenter.on = function(topic, func) { NotificationCenter.prototype.on = function(topic, func) {
if (!NotificationCenter.topics[topic]) { if (!this.topics[topic]) {
NotificationCenter.topics[topic] = []; this.topics[topic] = [];
} }
var token = ( ++NotificationCenter.subUid ).toString(); var token = ( ++this.subUid ).toString();
NotificationCenter.topics[topic].push({ this.topics[topic].push({
token: token, token: token,
func: func func: func
}); });
@ -32,18 +34,19 @@ define(
return token; return token;
} }
NotificationCenter.off = function(token) { NotificationCenter.prototype.off = function(token) {
for(var m in NotificationCenter.topics) { for(var m in this.topics) {
if (NotificationCenter.topics[m]) { if (this.topics[m]) {
for(var i = 0, j = NotificationCenter.topics[m].length; i < j; i++) { for(var i = 0, j = this.topics[m].length; i < j; i++) {
if (NotificationCenter.topics[m][i].token === token) { if (this.topics[m][i].token === token) {
NotificationCenter.topics[m].splice(i, 1); this.topics[m].splice(i, 1);
return token; return token;
} }
} }
} }
} }
return this;
} }
return NotificationCenter; return NotificationCenter;