zoukankan      html  css  js  c++  java
  • 观察者模式之ES6实现(一)

    一、参考链接

    https://github.com/JacksonTian/eventproxy/tree/master/lib

    二、代码实现

    // eventProxy.js
    'use strict';
    const eventProxy = {
        onObj: {},
        oneObj: {},
        on: function(key, fn) {
            if(this.onObj[key] === undefined) {
                this.onObj[key] = [];
            }
            this.onObj[key].push(fn);
        },
        one: function(key, fn) {
            if(this.oneObj[key] === undefined) {
                this.oneObj[key] = [];
            }
            this.oneObj[key].push(fn);
        },
        off: function(key) {
            this.onObj[key] = [];
            this.oneObj[key] = [];
        },
        trigger: function() {
            let key, args;
            if(arguments.length == 0) {
                return false;
            }
            key = arguments[0];
            args = [].concat(Array.prototype.slice.call(arguments, 1));
    
            if(this.onObj[key] !== undefined
              && this.onObj[key].length > 0) {
                for(let i in this.onObj[key]) {
                    this.onObj[key][i].apply(null, args);
                }
            }
            if(this.oneObj[key] !== undefined
              && this.oneObj[key].length > 0) {
                for(let i in this.oneObj[key]) {
                    this.oneObj[key][i].apply(null, args);
                    this.oneObj[key][i] = undefined;
                }
                this.oneObj[key] = [];
            }
        }
    };
    
    export default eventProxy;
  • 相关阅读:
    javaSE基础(三)
    javaSE基础(二)
    javaSE基础(一)
    文件目录爬虫
    前自增 与 后自增
    查找 与 排序 总结
    python 使用 grpc
    python3.7 安装 uwsgi
    go
    go
  • 原文地址:https://www.cnblogs.com/camille666/p/pub_sub_design_pattern_1.html
Copyright © 2011-2022 走看看