码迷,mamicode.com
首页 > Web开发 > 详细

JS 事件派发器EventDispatcher

时间:2015-07-16 09:29:52      阅读:480      评论:0      收藏:0      [点我收藏+]

标签:

在Java和AS中经常用到EventDispatcher,写了一个JS版本的。

addListener :添加事件监听器
removeListener:移除事件监听器
dispatchEvent:派发事件
 
/**
 * Created by taozh on 2015/7/11.
 * Mail:wiui@hotmail.com
 */

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

 

JS 事件派发器EventDispatcher

标签:

原文地址:http://www.cnblogs.com/zhtui/p/4625923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!