Event Aggregator

本文介绍了一个简单的事件聚合器实现方式,包括事件的订阅与发布功能。通过JavaScript代码展示了如何创建事件及事件处理函数,并实现事件的添加、移除和触发。
/**
 * Created with JetBrains WebStorm.
 * User: 宇乔
 * Date: 13-8-2
 * Time: 下午3:01
 * To change this template use File | Settings | File Templates.
 */

function Event(name) {

    var handlers = [];

    this.getName = function () {
        return name;
    }

    this.addHandler = function (handler) {
        handlers.push(handler);
    }
    this.removeHandler = function (handler) {
        handlers.forEach(function (item, i) {
            if (item == handler) {
                handler.splice(i, 1);
            }
        })
    }

    this.fire = function (eventArgs) {
        handlers.forEach(function (h) {
            h(eventArgs);
        })
    }
}


function EventAggregator() {
    var events = [];

    function getEvent(name) {
        var fn;
        events.forEach(function (item) {
            if (item.getName() == name) {
                fn = item;
                return;
            }
        });
        return fn;
    }

    this.subscribe = function (eventName, handler) {

        var event = getEvent(eventName);

        if (!event) {
            event = new Event(eventName);
            events.push(event);
        }
        event.addHandler(handler);
    }

    this.publish = function (eventName, eventArgs) {

        var event = getEvent(eventName);
        if (!event) {
            event = new Event(eventName);
            events.push(event);
        }
        event.fire(eventArgs);
    }
}

  

转载于:https://www.cnblogs.com/Mr-Joe/p/3232729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值