Mjs.Notifier = function () {
this.handlers = {};
};
Mjs.Notifier.prototype = {
publish: function (message_name, data) {
if (message_name == null || !message_name.length){
console.log("Notifier.publish: message_name is null");
} else if (this.handlers[message_name]) {
var numHandlers =this.handlers[message_name].length, i;
for (i = 0; i < numHandlers; ++i){
this.handlers[message_name][i](message_name, data);
}
}
},
subscribe: function (message_name, handler) {
if (message_name == null || !message_name.length ) {
console.log("Notifier.subscribe: message_name is null");
} else {
(this.handlers[message_name] || (this.handlers[message_name] = []));
this.handlers[message_name].push(handler);
}
},
unsubscribe: function (message_name, handler) {
if (message_name == null || !message_name.length) {
console.log("Notifier.unsubscribe: message_name is null");
} else if (this.handlers[message_name]) {
var handlerIndex = -1, i = 0;
var numHandlers = this.handlers[message_name].length;
for (i = 0; i < numHandlers; ++i) {
if (this.handlers[message_name][i] == handler) {
handlerIndex = i;
break;
}
}
if (handlerIndex != - 1) {
this.handlers[message_name].splice(handlerIndex, 1);
} else {
console.log("couldn't unsubscribe from " + message_name);
}
}
}
};
Mjs.notify = new Mjs.Notifier();