js; observer, subscriber pattern

//setting up callback functions 1onX, with subscribers

var otest6 = function(){

function oo(id){
var mm = {};
mm.id = id;
mm.callfns = [];
mm.callscopes = [];

this.fAddSubscriber = function(callfn,callscope){
mm.callfns.push(callfn);
mm.callscopes.push(callscope);
}

//simulate internally generated call-out
this.fcall_out = function(txt){
_fcall_out(txt);
};

function _fcall_out(txt){
fb(mm.id + ' request to shout:' + txt + ' To '
+ mm.callfns.length + ' subscribers');
for(var i = 0, ii= mm.callfns.length;i<ii;i++){
mm.callfns[i].apply(mm.callscopes[i],arguments);
}
}

this.fcall_in = function(args){
fb(mm.id + ' incoming:' + args);
};
}

var o1 = new oo('p1');
var o2 = new oo('p2');
var o3 = new oo('p3');

o1.fAddSubscriber(o2.fcall_in, o2);
o1.fAddSubscriber(o3.fcall_in,o3);
o1.fcall_out('do p2+p3 receive this ?');

o3.fAddSubscriber(o1.fcall_in, o1);
o3.fcall_out('does p1 receive this ?');
fb('COOL !')

};//end otest6
var app = new otest6();
function fb(p){
console.log(p);
}

Results in:
p1 request to shout:do p2+p3 receive this ? To 2 subscribers
p2 incoming:do p2+p3 receive this ?
p3 incoming:do p2+p3 receive this ?
p3 request to shout:does p1 receive this ? To 1 subscribers
p1 incoming:does p1 receive this ?
COOL !

Advertisements