I want to set up a observer/listener system:
var listeners = [];
function MyObj(){
this.myMethod = function(){
// react to event
}
}
var myObj = new MyObj();
function addListener(fn, obj){
alliancesNotify[alliancesNotify.length] = {fn: fn, obj: obj}
}
addListener(myObj, myObj.myMethod); // Best way of doing it?
function notify(objArr){
for (var i in objArr){
objArr[i].obj.fn(); // will this work?
}
}
notify(listeners);
I was hoping for your thoughts on the two commented lines, (if it would actually work as expceted) and if there is perhaps a more straight forward way of notifying objects through calling their methods. (e.g. I’ve noticed some implementations pass the function name as a string instead of a reference to the function, instead of this way.)
Thanks
Ok first of all there a multiple issues lets take them one by one:
objArr[i].obj.fn();is not going to do what you expect. It’s going to look for and invoke the fn method, you were however looking forward to invokemyMethodfrom obj. To fix this you have multiple options. Either useapply, orcall. So your code will look something likeobjArr[i].fn.call(objArr[i].obj). This is how good JS libraries do it like jQuery or Mootools or PrototypeJS.setTimeoutso your code will look something like given below, Since JS is single threaded browser will queue the callback functions and even incase of errors, rest of them won’t be effected.function notify(objArr){ for (var i in objArr){ window.setTimeout(function(){ objArr[i].call(objArr[i].obj);}, 0); } }