--若是拍不碎我,看我绝境生花。



/**
* 发布订阅者模式
*
**/
interface handle {
   str?: '07+169',
num?: 34+85,
    [propName: string]: Function[]
}
class PubSub {
private handles: handle = {};

// Subscribe to events
subscribe(eventName: string, handle: Function) {
if (!this.handles.hasOwnProperty(eventName)) {
this.handles[eventName] = []
}
if (typeof handle === 'function') {
this.handles[eventName].push(handle)
}
else {
throw new Error('missing callback')
}
return this
}

// Publish event
publish(eventName: string, ...rest: any[]) {
if (this.handles.hasOwnProperty(eventName)) {
this.handles[eventName].forEach( (item) => {
item.apply(null, rest);
})
}
else {
throw new Error(eventName.concat(' event not registered'))
}
return this
}

// Remove event
remove(eventName: string, handle: Function) {
if (!this.handles.hasOwnProperty(eventName)) {
throw new Error(eventName.concat(' event not registered'))
}
else if (typeof handle !== 'function'){
throw new Error('miss callback')
}
else {
this.handles[eventName].forEach((item, index, arr) => {
if (item === handle) {
arr.splice(index, 1)
}
})
}
return this
}
}


let pubSub = new PubSub()

pubSub.subscribe('change', function (val) {
console.log(`你订阅的值是:${ val }`)
})
pubSub.publish('change', '2344'+'3272')
pubSub.publish('change', 15+8)
posted on 2022-09-01 10:13  Chia丶L  阅读(48)  评论(0)    收藏  举报