In my last post, extension of function (1): inheritance, this function of extended function has been implemented for inheritance.
According to the theory of the climbing of the article, I'm going to talk to you about it. Implement multicast events by extending the function.
Some friends may be familiar with the listener pattern, and some friends may not know much about them. But for events. I believe almost no one has ever used it.
In JS, we tend to use the following code like the way to write and invoke the event.
var eventdemoclass= function () {
//constructor
}
Eventdemoclass.prototype = (function () {
//private< C5/>return {
//public
ondosomestaff:null,
dosomestaff:function () {
//Some function code
if ( This. Ondosomestaff) {This
. Ondosomestaff (Object,args);}}}
();
var c=new eventdemoclass ();
C.ondosomestaff=function () {
alert ("Staff is done");
}
C.dosomestaff ()
It's easy to write and it works when there's only one way to register.
But what if we need to register for multicast events like C # events?
Ritual The core code is presented.
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); }
}
}
Or use the Eventdemo class that you just defined.
The calling code is as follows
var c=new eventdemoclass ();
var listener=function () {alert ("Staff is Done")}
C.addeventlistener ("Ondosomestaff", listener,c);
C.dosomestaff ();//will pop up the form
c.removeeventlistener ("Ondosomestaff", listener);
C.dosomestaff ()//will not pop the form
This multicast event is implemented.
This article comes from the "technology from Focus" blog, please be sure to keep this source http://mt830813.blog.51cto.com/7611383/1255777
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/prototype/