changed notification center to singleton

This commit is contained in:
logsol 2012-07-22 01:52:44 +02:00
parent 70d6fc08bd
commit 68d08f4606

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

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