In my previous blog "Extension function (1): Extend" already Extension ' function ' function to implement Extend.
Follow the leads I ' ll talk about extension ' Function ' to implement multicast Event.
Some friends may familiar and listener model,some friends May is not.
But Event I believe these are no one none used.
In Js,we usually use blew the 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 is 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.
Register Event Method//@param eventName: Event name//@param func: Registration method//@param executor: Execution context object if NULL, use default context
Function.prototype.AddEventListener = function (EventName, func, executor) {var eventfunc = function () {//Multicast event execution Critical method
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);
//Unregister method//@param eventName: Event name//@param funchandle: Unregister Method Object If it is not the original object used for registration,//will not be able to cancel the action 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); }
}
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/prototype/