how to implement observer pattern in javascript?

前端 未结 9 1573
执笔经年
执笔经年 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:20

    class EventObserver {
      constructor () {
        this.observers = []
      }
    
      subscribe (fn) {
        this.observers.push(fn)
      }
    
      unsubscribe (fn) {
        this.observers = this.observers.filter(subscriber => subscriber !== fn)
      }
    
      broadcast (data) {
        this.observers.forEach(subscriber => subscriber(data))
      }
    }
    

    Or you can use EventEmitter in NodeJs https://nodejs.org/api/events.html#events_class_eventemitter

提交回复
热议问题