You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
cancel(type,fn){if(message[type]!==undefined&&message[type]instanceofArray){letlen=message[type].length;message[type].forEach((item,index)=>{if(item===fn){// 为了完成对象之间的解耦,能取消注册的函数必须就是注册的函数message[type].splice(index,1);console.log('You had remove '+fn.name);}})}}
在观察者模式中,核心是三种方法:订阅, 取消订阅, 发送订阅。即:
我们通过
regist
函数订阅注册某种类型的事件执行序列,通过fire
函数去分发按序列执行某种类型的事件,通过cancel
函数去取消订阅。接下来,我们分步完成这三个函数:
上面的代码浅显易懂,接下来贴一下测试代码,看看我们是不是完成了整个流程控制:
以上就是最基本的观察者模式,也是书上所提到的,那么接下来的文章将会对此进行扩展,并且谈谈现在流行库的设计方法。
The text was updated successfully, but these errors were encountered: