深究JavaScript

理解Observer(观察者模式)

2020-02-02  本文已影响0人  收纳哥斯拉

参考文章:参考原文链接

概念

观察者模式广泛应用于JS中。observer观察者是一个集合(collections),当状态有变化的时候,观察者通知集合下的对象相应的改变状态。举例说明这个概念。

概念图

代码实例

想象一下你有多个元素,他们需要同时更新内容当一些事件状态发生改变(例如:input中键入文字)。 他们既可以订阅观察者发送的通知,也可以取消观察者发送的通知。 可以在线玩一玩有需要可下载源代码

// define a class
class Observable {
  // each instance of the Observer class
  // starts with an empty array of things (observers)
  // that react to a state change
  constructor() {
    this.observers = [];
  }

  // add the ability to subscribe to a new object / DOM element
  // essentially, add something to the observers array
  subscribe(f) {
    this.observers.push(f);
  }

  // add the ability to unsubscribe from a particular object
  // essentially, remove something from the observers array
  unsubscribe(f) {
    this.observers = this.observers.filter(subscriber => subscriber !== f);
  }

  // update all subscribed objects / DOM elements
  // and pass some data to each of them
  notify(data) {
    this.observers.forEach(observer => observer(data));
  }
}

The usecase example goes like this…

// some DOM references
const input = document.querySelector('.js-input');
const p1 = document.querySelector('.js-p1');
const p2 = document.querySelector('.js-p2');
const p3 = document.querySelector('.js-p3');

// some actions to add to the observers array
const updateP1 = text => p1.textContent = text;
const updateP2 = text => p2.textContent = text;
const updateP3 = text => p3.textContent = text;

// instantiate new Observer class
const headingsObserver = new Observable();

// subscribe to some observers
headingsObserver.subscribe(updateP1);
headingsObserver.subscribe(updateP2);
headingsObserver.subscribe(updateP3);

// notify all observers about new data on event
input.addEventListener('keyup', e => {
  headingsObserver.notify(e.target.value);
});

结果页

我还是想说一下为什么要了解它

其实随着Vue和React这些响应式框架的流行,observer设计模式已经不太需要自己去写原生代码了,但是对原生代码会告诉你一些第一性原则,比如:

  1. observer的本质是collection
  2. 如果observer是collection那么它也可以是iterator

那么接下来UI events它的处理模式竟然也可以用iterator来处理,瞬间有了一种天灵盖被钻孔的感觉。这可以更好的消除代码中的bug,提高质量和效率。

想要了解更多可以参考 --> “Learning JavaScript Design Patterns” by Addy Osmani

上一篇 下一篇

猜你喜欢

热点阅读