JavaScript Event Management

Source: Internet
Author: User
Tags event listener

When designing JavaScript xxsdk, consider the ability to involve the caller in the workflow and start using the callback function. As follows:

 This function (ARGS,CALLBACKFN) {      //dosomething        //then  if CALLBACKFN is a function       callbackfn ();};

Or in the Initialized incoming config.

 functionSDK (config) {varConfigs ={onInit:function() {}, OnFoo:function () {                },                //On ....            }; //Merging ParametersConfigs =$.extend (configs, config);  This. Foo =function(args) {//Do somethingConfigs.onfoo (); };}

But the problem comes, with the more functions, the first way is very annoying, each method parameter to follow one or more callback functions, the code is not clean, and only the user calls when the callback will be executed, for the method is not exposed to the user. The second way, the more functions, the longer the config, the construction code looks ugly, on the other hand, a method will only trigger a callback. Finally, the following method is used

Event Management

To define an event manager, the main idea is to have each event type correspond to a list of callbacks, which allows the external to be associated with the same event multiple times. Canceling an association removes a callback function from the list of functions for that event type. The trigger is to execute all the functions in the list again. And, of course, with the parameters.

 varEventmanger ={handlers: {},//type, binding eventAddHandler:function(type,handler) {if(typeof  This. handlers[type] = = "undefined") {                         This. Handlers[type] = [];//each event can be bound multiple times                    }                     This. Handlers[type].push (handler); }, RemoveHandler:function(type, handler) {varEvents = This. Handlers[type];  for(vari = 0, len = events.length; i < Len; i++) {                        if(Events[i] = =handler) {Events.splice (i,1);  Break; }}, Trigger:function(type) {if( This. Handlers[type]instanceofArray) {                        varHandlers = This. Handlers[type]; varargs = Array.prototype.slice.call (arguments, 1);  for(vari = 0, len = handlers.length; i < Len; i++) { handlers[i].apply ( NULL , args); }                    }                }            };

Then publish the associated and removed methods in the SDK:

// to an externally bound event             This function (Type, event) {                eventmanger.addhandler (type,event);            };             // Removing events             This function (Type, event) {                Eventmanger.removehandler (type, event);            };

The events are triggered individually during execution:

            This. init =function() {                //Do initEventmanger.trigger (' init ');            };  This. Start =function() {                //Do startEventmanger.trigger (' Start ');            };  This. connect =function() {Eventmanger.trigger (' Connect ');            };  This. Messages =function() {                varMsgs = []; Msgs.push ("How are you?"); Msgs.push ("I'm fine."); Eventmanger.trigger ( ' Messages ' , msgs);            };  This. Disconnect =function() {Eventmanger.trigger (' Disconnect '); };

The user is more convenient when they use it.

//Bind ConnectSdk. on(' Connect ',function() {Console.log (' Connect '); });//Binding MessagesSdk. on(' Messages ',function(data) {if(!data)return; if(DatainstanceofArray) {                 for(vari = 0; i < data.length; i++) {Console.log (data[i]); }            } Else{console.log (data); }       });

You can also bind, remove, and rebind.

var function {            console.log(' init ... ');        sdk.on (' init ', OnInit); Sdk.on (function  () {            console.log (' other init ');        }); SDK.  Off(' init ', oninit);        Sdk.init ();

All code:

    functionSDK () {varEventmanger ={handlers: {},//type, binding eventAddHandler:function(type,handler) {if(typeof  This. handlers[type] = = "undefined") {                         This. Handlers[type] = [];//each event can be bound multiple times                    }                     This. Handlers[type].push (handler); }, RemoveHandler:function(type, handler) {varEvents = This. Handlers[type];  for(vari = 0, len = events.length; i < Len; i++) {                        if(Events[i] = =handler) {Events.splice (i,1);  Break; }}, Trigger:function(type) {if( This. Handlers[type]instanceofArray) {                        varHandlers = This. Handlers[type]; varargs = Array.prototype.slice.call (arguments, 1);  for(vari = 0, len = handlers.length; i < Len; i++) {handlers[i].apply (NULL, args);            }                    }                }            }; //to an externally bound event             This. on =function(Type, event) {Eventmanger.addhandler (type,event);            }; //Removing events             This. Off =function(Type, event) {Eventmanger.removehandler (type, event);            };  This. init =function() {                //Do initEventmanger.trigger (' init ');            };  This. Start =function() {                //Do startEventmanger.trigger (' Start ');            };  This. connect =function() {Eventmanger.trigger (' Connect ');            };  This. Messages =function() {                varMsgs = []; Msgs.push ("How are you?"); Msgs.push ("I'm fine."); Eventmanger.trigger (' Messages ', msgs);            };  This. Disconnect =function() {Eventmanger.trigger (' Disconnect ');            };  This. AutoRun =function() {                 This. Init ();  This. Start ();  This. connect ();  This. messages ();  This. Disconnect ();                    }; }        varSDK =NewSDK (); varOnInit =function() {Console.log (' Init ... ');        }; Sdk.on (' Init ', OnInit); Sdk.on (' Start ',function() {Console.log (' Start ');        }); Sdk.on (' Connect ',function() {Console.log (' Connect ');        }); Sdk.on (' Messages ',function(data) {if(!data)return; if(DatainstanceofArray) {                 for(vari = 0; i < data.length; i++) {Console.log (data[i]); }            } Else{console.log (data);        }        }); Sdk.on (' Disconnect ',function() {Console.log (' Disconnect ');        });        Sdk.autorun (); Sdk.on (' Init ',function() {Console.log (' Other init ');        }); Sdk.off (' Init ', OnInit); Sdk.init ();
View Code

Execution Result:

Summary: The way events are handled is more concise and more scalable. The event mechanism of jquery does not bind event listener functions to DOM elements, but rather manages them based on the data cache module. Here, for reference, all listener objects of the same event type Handleobj constitute an array of listener objects handles. Because DOM manipulation is not involved, it is relatively simple.

JavaScript Event Management

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.