原来通信模式没有规律,向一张纵横交错的网
观察者模式: 数据总线
class Emitter {
_subs: {};
construtor (params?: object) {
return(params && this.mixin(params));
}
mixin (params) {
for (let key in Emitter.prototype) {
params[key] = Emitter.prototype[key];
}
return params;
}
on
once
off
emit
}
on (event, fn) {
(this._subs[event] = this._subs[event] || []).push(fn);
return this;
}
once (event, fn) {
function on () {
this.off(event, fn);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
}
emit (event, ...args?: any) {
let callbacks = this._subs[event];
callbacks.forEach((item)=>{
item.apply(this.args);
});
return this;
}
// off
off (event, fn) {
if (0 === arguments.length) {
this._subs = {};
return this;
}
let callbacks = this._subs[event];
if (!callbacks || !callbacks.length === 0) return this;
if (1 === arguments.length) {
delete this._subs[event];
return this;
}
let cb;
for (let i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。