javascriptVue+ElementUI

2018-03-20 js订阅发布模式使用场景

2018-03-20  本文已影响0人  怪兽别跑biubiubi
<!DOCTYPE html>
    <html lang="en">
       <head>
           <meta charset="UTF-8">
           <meta name="viewport" content="width=device-width, initial-scale=1.0">
           <meta http-equiv="X-UA-Compatible" content="ie=edge">
           <title>Document</title>
       </head>
       <body>
        <script>
            class Event {
               constructor() {
                  this.books = {}
               }

               // 订阅
               subscrible(event, func) {
                  this.books[event] ? this.books[event] = this.books[event] : this.books[event] = []
                  this.books[event].push(func)
               }

               // 取消订阅
               unsubscrible(event, func) {
                  if(func) {
                     let index = this.books[event].indexOf(func)
                     this.books[event].splice(index, 1)
                  }else {
                     this.books[event] = []
                  }
               }
  
              // 触发
              trigger(event) {
                 this.books[event].forEach(func => {
                    func && func()
                 })
              }
          }

          let event = new Event

          let test = () => {
             console.log("吃饱了")
          }

          let shuijiao = () => {
             console.log("睡着了")
          }

          let shuijiao2 = () => {
             console.log("睡醒了")
          }

         event.subscrible("chifan", test)
         event.subscrible("shuijiao", shuijiao)
         event.subscrible("shuijiao", shuijiao2)

         event.unsubscrible("shuijiao")

         console.log(event.books)

         document.addEventListener('click', () => {
           event.trigger("chifan")
           event.trigger("shuijiao")
         })
    </script>
 </body>
</html>
上一篇下一篇

猜你喜欢

热点阅读