function Signal() {
this.handlers = [];
}
Signal.prototype.connect = function (handler) {
if (this.handlers.indexOf(handler) == -1) {
this.handlers.push(handler);
}
};
Signal.prototype.disconnect = function (handler) {
var index = this.handlers.indexOf(handler);
if (index == -1) {
throw new Error("handler hasn't been connected");
} else {
var temp = [];
for (var i = 0; i < this.handlers.length; ++i) {
if (i == index) continue;
temp.push(this.handlers[i]);
}
this.handlers = temp;
}
};
Signal.prototype.emit = function () {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < this.handlers.length; ++i) {
this.handlers[i].apply(null, args);
}
};
Signal.prototype.clearHandlers = function () {
this.handlers = [];
};
function notify(user, message) {
console.log('%s recieved message: %s', user, message);
};
var signal = new Signal();
signal.connect(notify);
signal.emit("John", "PHP is sucks");