zoukankan      html  css  js  c++  java
  • 事件订阅分发模型

    最近看了下各位大师写的事件订阅分发的模型很有感触,js果然强大到行如流水,下面这段模型摘自汤姆大叔的深入理解Javascript,非常感谢原作者

    原文链接:http://www.sxrczx.com/docs/js/2305513.html

    function Event(name) {
                var handlers = [];
    
                this.getName = function () {
                    return name;
                };
    
                this.addHandler = function (handler) {
                    handlers.push(handler);
                };
    
                this.removeHandler = function (handler) {
                    for (var i = 0; i < handlers.length; i++) {
                        if (handlers[i] == handler) {
                            handlers.splice(i, 1);
                            break;
                        }
                    }
                };
    
                this.fire = function (eventArgs) {
                    handlers.forEach(function (h) {
                        h(eventArgs);
                    });
                };
            }
    
            function EventAggregator() {
                var events = [];
    
                function getEvent(eventName) {
                    return $.grep(events, function (event) {
                        return event.getName() === eventName;
                    })[0];
                }
    
                this.publish = function (eventName, eventArgs) {
                    var event = getEvent(eventName);
    
                    if (!event) {
                        event = new Event(eventName);
                        events.push(event);
                    }
                    event.fire(eventArgs);
                };
    
                this.subscribe = function (eventName, handler) {
                    var event = getEvent(eventName);
    
                    if (!event) {
                        event = new Event(eventName);
                        events.push(event);
                    }
    
                    event.addHandler(handler);
                };
            }
  • 相关阅读:
    docker建镜像
    注册路由的简易实现
    docker的小技巧记录(如果使用了更多会继续添加)
    Alembic使用
    SQLAlchemy的常用数据类型
    记录SQLAlchemy的基本使用
    linux创建桌面快捷方式
    vim编辑器命令
    redis发布订阅
    谨慎使用mysql的utf8
  • 原文地址:https://www.cnblogs.com/johnx/p/6061640.html
Copyright © 2011-2022 走看看