背景
先简单说一下什么是观察者模式。观察者模式又叫做发布订阅模式,订阅者可以订阅一些消息,发布者可以发布一些消息。
举个?:小王(订阅者)订阅了知乎周刊(消息),那么知乎(发布者)发布知乎周刊(消息),小王就会收到。过了几天,小王又不想看知乎周刊了,那他就可以取消订阅,知乎再发布周刊,他就收不到了。
所以说这个系统会包含一个订阅的方法、发布的方法和取消订阅的方法。
代码
var observer = {
//消息队列
_message :{},
/**
* 订阅消息
*
* @param {string} type 消息类型
* @param {function} fn 消息要执行的回调
*/
on: function(type, fn) {
if (!type) {
return ;
}
if (typeof fn !== 'function') {
console.error('fn must be a function');
return ;
}
this._message[type] = fn;
},
/**
* 取消订阅
*
* @param {string} type 消息类型
*/
off: function(type) {
if(!type) {
return ;
}
this._message[type] = null;
},
/**
* 发布消息
*
* @param {*} type 消息类型
*/
emit: function(type) {
if (!type) {
return ;
}
const args = [...arguments];
args.shift();
if (typeof this._message[type] === 'function') {
this._message[type].apply(this, args);
}
}
};
我们来简单测试一下:
//订阅一个test类型的消息
//监听到test类型的消息发布的时候,执行回调,输出参数的值
observer.on('test', (a, b) => {
console.log('a', a);
console.log('b', b);
});
//发布一个test类型的消息
observer.emit('test', 'aaa', 'bbb');
// a aaa
// b bbb
//取消订阅test类型的消息
observer.off('test');
//发布test类型的消息
observer.emit('test', 'aaa', 'bbb');
//没有输出