欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Event Aggregator

程序员文章站 2022-06-18 23:22:55
...
/**
 * 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);
    }
}