JS 事件派发器EventDispatcher

在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"});

 

你可能感兴趣的:(dispatcher)