zoukankan      html  css  js  c++  java
  • eventEmitter的简单实现

    class Emitter {
        constructor() {
            this.cb = {};
        }
        on(name, fn) {
            if (!this.cb[name]) {
                this.cb[name] = [fn];
            } else {
                this.cb[name].push(fn);
            }
        }
        emit(name, ...args) {
            this.cb[name].forEach(fn => fn.call(this, ...args));
        }
        remove(name, fn) {
            let index = this.cb[name].indexOf(fn);
            if (index !== -1) {
                this.cb[name].splice(index, 1);
            }
        }
        once(name, fn) {
            // 调用一次的实现,封装传入函数,一次调用后remove
            function onceFn(...args) {
                fn.call(this, ...args);
                this.remove(name, onceFn);
            }
            this.on(name, onceFn);
        }
    }
    
    // 测试代码
    let emitter = new Emitter();
    let test = function (value) {
        console.log('test' + value);
    };
    let test_again = function () {
        console.log('again');
    };
    emitter.on('test', test);
    emitter.on('test', test_again);
    emitter.emit('test', 123);
    
    // emitter.once('once', test);
    // emitter.emit('once', 123);
    // emitter.emit('once', 456);
  • 相关阅读:
    UPC 5130 Concerts
    poj 1079 Calendar Game
    2018 ACM-ICPC 中国大学生程序设计竞赛线上赛
    CF932E
    浅谈Tarjan算法
    拉格朗日差值
    扩展欧几里得算法(exgcd)
    欧拉定理
    莫比乌斯反演
    除法分块
  • 原文地址:https://www.cnblogs.com/chh1995/p/14944248.html
Copyright © 2011-2022 走看看