zoukankan      html  css  js  c++  java
  • 实现观察者模式

    class EventEmitter {
        constructor(){
            this.messageBox = {}
        }
    
        on(eventName,fn){
            const callbacks = this.messageBox[eventName] || []
            callbacks.push(fn)
            this.messageBox[eventName] = callbacks
        }
    
        emit(eventName,...args){
            if (this.messageBox[eventName]) {
                const callbacks = this.messageBox[eventName]
                callbacks.forEach((callback)=>{
                    callback(...args)
                })
            } else{
                console.log(`${eventName} is not defined`)
            }
        }
    
        off(eventName,fn){
            if (this.messageBox[eventName]) {
                const index = callbacks.indexOf(fn)
                if (index !== -1) callbacks.slice(index,1)
                else console.log(`${fn} is not defined`)
            } else {
                console.log(`${eventName} is not defined`)
            }
        }
    
        once(eventName,fn){
            var onlyOnce = function() {
                fn()
                this.off(eventName,onlyOnce)
            }
            this.on(eventName,onlyOnce);
        }
    }
  • 相关阅读:
    3. CSS 的复合选择器
    2. CSS文本属性
    1. CSS字体属性
    pm2 语法
    Emmet语法
    排序算法之 '归并排序'
    CCS
    CCS
    CCS
    怀旧编程之原生js实现简易导航栏
  • 原文地址:https://www.cnblogs.com/AwenJS/p/12697158.html
Copyright © 2011-2022 走看看