它主要包含了两类对象:
- 发布者:一个或多个,每当有重要事情发生后,会通知订阅者;
- 订阅者,追随一个或多个发布者,监听它们的通知,并作出相应的反应;
DOM中的时间绑定是经典的订阅-发布模式的应用
订阅-发布模式的主要组成:
- 由回调函数构成的订阅者数组;
- 用于添加和删除订阅者的addSubscriber()和removeSubscriber()方法;
- publish()方法,授受并传递数据给订阅者;
- make()方法,将任意对象转变为一个发布者并为其添加上诉方法
代码:
let observer = {
//订阅
addSubscriber: function (callback) {
this.subscribers[this.subscribers.length] = callback;
},
//退订
removeSubscriber: function (callback) {
for (let i = 0; i < this.subscribers.length; i++) {
if (this.subscribers[i] === callback) {
delete (this.subscribers[i]);
}
}
},
//发布
publish: function (what) {
for (let i = 0; i < this.subscribers.length; i++) {
if (typeof this.subscribers[i] === 'function') {
this.subscribers[i](what);
}
}
},
// 将对象o具有观察者功能
make: function (o) {
for (let i in this) {
o[i] = this[i];
o.subscribers = [];
}
}
};
//发布者
let blogger = {
writeBlogPost: function () {
let content = 'Today is ' + new Date();
this.publish(content);
}
};
observer.make(blogger);
//订阅者
let jack = {
read: function (what) {
console.log('I have read that ' + what)
}
};
//添加订阅
blogger.addSubscriber(jack.read);
blogger.writeBlogPost();
//I have read that Today is Wed Sep 05 2018 19:47:51 GMT+0800 (中国标准时间)
//删除订阅
blogger.removeSubscriber(jack.read);
blogger.writeBlogPost()
//没有响应
参考自:《javascript面向对象编程指南(第2版)》