Monday, March 21, 2016

#javascript observer pattern - using object literal notation - very simple

var obj1 = {
  subscribers:[],
  addSubscriber:function(subObj)
   {
       obj1.subscribers.push(subObj);
   },
   notifySubscribers:function()
   {
        for(var subIndex in obj1.subscribers)
        {
            obj1.subscribers[subIndex].onObj1Change();
        }
   },
   doStuff:function()
   {
       obj1.notifySubscribers();
   }
}


var obj2 = {
   init:function(){
       obj1.addSubscriber(obj2);
   },
   
   onObj1Change:function()
   {
      console.log("Obj1 changed and I was notified. I'm gonna do stuff now");

   }
}

No comments:

Post a Comment

There was an error in this gadget