Extension Function (2): Multicast Event - 面向对象网,web开发,Prototype,学习,对象 - 面向对象技术开发

面向对象技术开发

会员投稿 投稿指南 站长资讯通告:
您的位置: 首页 > Web开发 > Prototype > 正文

Extension Function (2): Multicast Event

来源: www.bianceng.cn 阅读:

In my previous blog 《Extension Function (1): Extend》 already extension "Function" function to implement Extend.

follow the lead i'll talk about extension "Function" to implement Multicast Event.

Some friends may familiar with listener model,Some friends may be not.

But event I believe these is no one none used.

In Js,We usually use blew code to implement event.

vareventDemoClass= 

function() {
//constructor
}
eventDemoClass.prototype = (function() {
//private
return{
//public  
OnDoSomeStaff:null,
DoSomeStaff:function(){
// some function code
if(this.OnDoSomeStaff){
this.OnDoSomeStaff(object,args);
}
}
};
})();
varc=neweventDemoClass();
c.OnDoSomeStaff=function(){
alert("staff was done");
}
c.DoSomeStaff()

It's easy and effective when just only one function to regist.

But if we need regist multicast event as we used in c#.

what can we do?

As usual,here is the core code.

//注册事件方法
//@param eventName:事件名
//@param func:进行注册的方法
//@param executor:执行上下文对象 如果为空则使用默认上下文
Function.prototype.AddEventListener =
function (eventName, func, executor) {
    var eventFunc = function () {//多播事件执行关键方法
        var eventArray = arguments.callee.FunctionArray;
        var executorArray = arguments.callee.Executor;
        for (var i = 0; i < eventArray.length; i++) {
            var executor = executorArray[i];
            if (!executor) {
                executor = this;
            }
            eventArray[i].apply(executor, arguments);
        }
    }
    if (!this[eventName] || !this[eventName].FunctionArray) {
        this[eventName] = eventFunc;
        this[eventName].FunctionArray = [];
        this[eventName].Executor = [];
    }
    this[eventName].FunctionArray.push(func);
    this[eventName].Executor.push(executor);
}
//取消注册方法
//@param eventName:事件名
//@param funcHandle:取消注册的方法对象 如果不是注册时使用的原对象,
//将无法进行取消动作
Function.prototype.RemoveEventListener =
function (eventName, funcHandle) {
    if (this[eventName] && this[eventName].FunctionArray) {
        var index = this[eventName].FunctionArray.RemoveObject(funcHandle);
        if (index >= 0) {
            this[eventName].Executor.RemoveIndex(index);
        }
    }
}

查看本栏目更多精彩内容:http://www.bianceng.cn/webkf/prototype/

Tags:
相关文章列表: