Event Aggregator

葛桐
2023-12-01
/**
 * 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

 类似资料:

相关阅读

相关文章

相关问答