JS 事件派发器EventDispatcher

页面导航:首页 > 网络编程 > JavaScript > JS 事件派发器EventDispatcher

JS 事件派发器EventDispatcher

来源: 作者: 时间:2016-02-01 09:32 【

在Java和AS中经常用到EventDispatcher,写了一个JS版本的。addListener :添加事件监听器removeListener:移除事件监听器dispatchEvent:派发事件 ** * Created by taozh on 2015 7 11 * Mail:[email protected]
在和AS中经常用到EventDispatcher,写了一个JS版本的。
 
addListener :添加事件监听器
removeListener:移除事件监听器
dispatchEvent:派发事件
 
 
/**
 * Created by taozh on 2015/7/11.
 * Mail:
 */

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

 

 
Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<