vue订阅者模式
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <!-- addeventlistener('click',fn) @click=fn $emit('事件名称','事件内容') --> <script type="text/javascript"> // obj.addlistener('click',fn1) // obj.addlistener('click',fn2) // obj.addlistener('click',fn3) // // obj.emit('click','事件内容') var obj = { eventFns:{ // click:[fn1,fn2,fn3] }, addListener:function(eventName,fn){ if(this.eventFns[eventName]){ this.eventFns[eventName].push(fn) }else{ this.eventFns[eventName] = [] this.eventFns[eventName].push(fn) } }, emit:function(eventName,content){ this.eventFns[eventName].forEach(function(item){ item(content) }) }, removeListener:function(eventName,fn){ var index = this.eventFns[eventName].indexOf(fn) if(index!=-1){ this.eventFns[eventName].splice(index,1) } } } obj.addListener('click',function(e){ console.log(e) console.log('这是订阅者1') }) obj.addListener('click',function(e){ console.log(e) console.log('这是订阅者2') }) var fn1 = function(){ console.log('这是订阅者3') } obj.addListener('click',fn1) obj.removeListener('click',fn1) obj.emit('click',{ eventname:'click', timestamp:new Date() }) document.querySelector('body').removeEventListener('事件名称',fn1) </script> </body> </html>