Event Aggregator

/**
 * 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);
    }
}

  

posted @ 2013-08-02 15:37  高捍得  阅读(234)  评论(0编辑  收藏  举报