手写mini订阅发布模式
subscribe.js
1 (function(){ 2 class Subscribe { 3 constructor() { 4 // 事件池 5 this.$pond = [] 6 } 7 // 追加事件 8 add(func) { 9 // 事件去重 10 const flag = this.$pond.some(item => item === func) 11 if(flag) return 12 this.$pond.push(func) 13 } 14 // 删除事件 15 remove(func) { 16 const index = this.$pond.findIndex(item => item === func) 17 if(index < 0) return 18 this.$pond.splice(index, 1, null) 19 } 20 // 执行事件 21 fire(...args) { 22 this.$pond = this.$pond.filter(func => func !== null) 23 this.$pond.forEach(func => { 24 func.call(this, ...args) 25 }) 26 } 27 } 28 window._subscribe = new Subscribe() 29 })()
test.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 </head> 9 <body> 10 <button>发火</button> 11 <script src="./subscribe.js"></script> 12 <script> 13 const btn = document.querySelector('button') 14 btn.onclick = function(){ 15 _subscribe.fire() 16 } 17 18 function fn1(){ 19 console.log(1) 20 } 21 _subscribe.add(fn1) 22 23 function fn2(){ 24 console.log(2) 25 _subscribe.remove(fn1) 26 } 27 _subscribe.add(fn2) 28 29 function fn3(){ 30 _subscribe.remove(fn3) 31 console.log(3) 32 } 33 _subscribe.add(fn3) 34 35 </script> 36 </body> 37 </html>