class SubScrible{
constructor(){ //事件对象,存放订阅对象 this.events = {}; }
//订阅事件方法 subscribe(type,callback){ if(typeof this.events[type] === 'undefined'){ //一个type可以订阅多个事件 this.events[type] = [callback]; }else{ //存在则在尾部添加进去 this.events[type].push(callback); } } //触发事件方法 emit(type,...rest){ if(this.events[type]){ let array = this.events[type]; //进行遍历 for (let i = 0; i < array.length; i++){ const reducer = array[i]; reducer(rest); } } } //取消订阅 cancelSubscribe(type,callback){ if(!type){ this.events = {}; }else if(this.events[type]){ this.events[type] = this.events[type].filter(fn => fn !== callback) } } //只执行一次订阅事件然后移除 once(type,callback){ const fn = () => { callback(); this.cancelSubscribe(type,fn) }; this.subscribe(type,fn) }
}
使用
let test = new SubscribeModel(); const handle = (...pyload) => console.log(pyload) test.subscribe('click', handle) test.emit('click', 100, 200, 300, 100) test.cancelSubscribe('click', handle) test.once('dbclick', function() { console.log('click') }) test.emit('dbclick', 100);