var Listener = function(name, subject){
function update(evt) {
evt(this);
}
var obj = {
name: name,
update: update
};
if (subject) {
subject.register(obj);
}
return obj;
};
var Subject = function(){
var listeners = [];
function notify(evt) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].update(evt);
}
}
function register(listener) {
listeners.push(listener);
}
function unregister(listener) {
var buf = [];
for (var i = 0; i < listeners.length; i++) {
if (listener != listeners[i]) {
buf.push(listeners[i]);
}
}
listeners.length = 0;
listeners = buf;
}
return {
listeners: listeners,
notify: notify,
register: register,
unregister: unregister
};
};
var s = Subject();
l1 = Listener('LISTENER1', s);
l2 = Listener('LISTENER2', s);
l3 = Listener('LISTENER3');
s.notify(function(obj){ console.log('hello, ' + obj.name)});
console.log('---');
s.register(l3);
s.notify(function(obj){ console.log('hello, ' + obj.name)});
console.log('---');
s.unregister(l2);
s.notify(function(obj){ console.log('hello, ' + obj.name)});