vue訂閱者模式
阿新 • • 發佈:2019-03-18
ice back function () round clas doctype set tlist
<!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>
vue訂閱者模式