观察者模式
-
发布&订阅
-
一对多
-
优点:更加解耦,支持广播通信
-
缺点:大量观察者,广播有性能问题
// 主题对象 class Subject { constructor() { this.state = {}; this.observers = []; } getState() { return this.state; } setState(state) { this.state = state; this.notifyAllObservers(); } notifyAllObservers() { this.observers.forEach(observer => { observer.update(); }); } attach(observer) { this.observers.push(observer); } } // 观察者 class Observer { constructor(name, subject) { this.name = name; this.subject = subject; this.subject.attach(this); } update() { console.log(`${this.name} update, state: ${this.subject.getState()}`); } } // 测试 let sub = new Subject(); let ob1 = new Observer('Confidence', sub); let ob2 = new Observer('Java', sub); let ob3 = new Observer('NodeJs', sub); sub.setState(1);
-
场景
- 网页事件绑定
$('#btn').click(function() { console.log(1); }); $('#btn').click(function() { console.log(2); });
- Promise
function loadImg() { const promise = new Promise((resolve, reject) => { var img = document.createElement('img'); img.onload = function() { resolve(img); } img.onerror = function() { reject('图片加载失败); } img.src = 'https://....xxx.png'; }); return promise; } loadImg().then(res => { return res; }).then(res => { console.log(res); })
- jQuery callbacks
var callbacks = $.Callbacks(); callbacks.add(function(info) { console.log('fn1', info); }); callbacks.add(function(info) { console.log('fn2', info); }); callbacks.fire('arg1'); callbacks.fire('arg2');
- nodejs自定义事件
- 网页事件绑定
网友评论