JSイベントディスパッチEventDispatcher

5987 ワード

JavaやASではEventDispatcherがよく使われ、JSバージョンが書かれています.
addListener :       
removeListener:       
dispatchEvent:    
 
/**
 * Created by taozh on 2015/7/11.
 * Mail:[email protected]
 */

var z = {};
z.EventDispatcher = function () {
    this.__z_e_listeners = {};
};

z.EventDispatcher.prototype.addListener = function (type, fun, context) {
    var list = this.__z_e_listeners[type];
    if (list === undefined) {
        list = [];
        this.__z_e_listeners[type] = list;
    }
    var lis = {
        func: fun,
        context: context
    };
    list.push(lis);
    return lis;
};
z.EventDispatcher.prototype.removeListener = function (type, fun, context) {
    var list = this.__z_e_listeners[type];
    if (list !== undefined) {
        var size = list.length;
        for (var i = 0; i < size; i++) {
            var obj = list[i];
            if (obj.func === fun && obj.context === context) {
                list.splice(i, 1);
                return;
            }
        }
    }
};
z.EventDispatcher.prototype.dispatchEvent = function (type, event) {
    var list = this.__z_e_listeners[type];
    if (list !== undefined) {
        var size = list.length;
        for (var i = 0; i < size; i++) {
            var ef = list[i];
            var fun = ef.func;
            var context = ef.context;
            if (context != null) {
                fun.call(context, event);
            } else {
                fun(event);
            }
        }
    }
};

Test Code
/**
 * Test Code
 */
var listener1 = function () {
    console.log("1");
};
var listener2 = function () {
    console.log("2");
};
var ed = new z.EventDispatcher();
console.log("add listener1");
ed.addListener("test", listener1);

console.log("add listener2");
ed.addListener("test", listener2);

console.log("dispatch event");
ed.dispatchEvent("test", {event: "as you link"});

console.log("removeL listener2");
ed.removeListener("test", listener2);

console.log("dispatch event");
ed.dispatchEvent("test", {event: "as you link"});