how to implement observer pattern in javascript?

前端 未结 9 1650
执笔经年
执笔经年 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条回答
  •  Happy的楠姐
    2021-01-30 08:25

    The observer pattern is all about updating an object and having those updates automatically send out an event that gives info about what was updated.

    For example:

    function ObserverList(){
      this.observerList = []
      this.listeners = []
    }
    
    ObserverList.prototype.add = function( obj ){
      this.observerList.push(obj)
      this.listeners.forEach(function(callback){
        callback({type:'add', obj:obj})
      })
    }
    
    ObserverList.prototype.onChange = function(callback){
      this.listeners.push(callback)
    }
    

    Here's a module of the observer pattern in javascript, you can take a look at the source code fore more info: https://github.com/Tixit/observe

提交回复
热议问题