how to implement observer pattern in javascript?

前端 未结 9 1548
执笔经年
执笔经年 2021-01-30 07:29

Hi I\'m tyring to implement observer pattern in JavaScript:

My index.js:

$(document).ready(function () {
  var ironMan = new Movie();
           


        
9条回答
  •  有刺的猬
    2021-01-30 08:12

    In JavaScript, there is no point to implement pure observer pattern as in Java, because JavaScript has this little thing called functional programming. So just use something like http://api.jquery.com/category/callbacks-object/ instead of your ObserverList.

    If you still want to use your object, then everything depends on what do you want to pass to ObserverList.Add. If it is some object, then you need to write

    for( i = 0; i < observers.Count; i++) { 
      observers[i].Notify("some data"); 
    }
    

    If it is a function then you need to write

    for( i = 0; i < observers.Count; i++) { 
      observers[i]("Some data"); 
    }
    

    Also you can use Function.apply() or Function.call() to supply this to your function

提交回复
热议问题