订阅发布模式,对前端来说这已经是老生常谈了
观察者模式,又称为订阅发布模式,其实质就是在内存中开辟一个对象(事件车),专门用于接口的注册(订阅)与触发(发布)
以前的憨憨前端工程师就是这样的方法在脚本中注册大量的接口,从而实现开发人员可以在闭包模块中调用其他人的接口,最后导致这个事件车拥有大量的接口,后期维护相当复杂
另一个方面,事件车常常用于某些框架的组件通信
class EventEmiter {
constructor() {
this.cache = []
}
emit(type,...args) {
if(this.cache[type] && this.cache[type].length > 0) {
let i = -1,len = this.cache[type].length
while(++i < len ) {
this.cache[type][i].call(null,...args)
}
} else {
return new TypeError('this cache '+ type +' is null')
}
}
register(type,fn){
if(this.cache[type] === undefined){
this.cache[type] = [fn]
} else {
this.cache[type].push(fn)
}
return ()=> {
this.remove(type,fn)
}
}
remove(type,fn){
if(!this.cache[type] || this.cache[type].length === 0) {
return new TypeError('this cache '+ type +' is null')
}
let i= this.cache[type].length
while(--i>=0 ) {
if(this.cache[type] === fn ) {
return this.cache.splice(i,1)
}
}
}
}
网友评论