Upgraded magic version of jQuery custom binding
JQuery custom binding
First, let's take a look at the use of jQuery's custom binding. You can use bind or live to subscribe to an event (you can also use on after 1.7). The Code is as follows:
$(#myElement).bind('customEventName',function(e){ ... });$(.elementsClass).live('customEventName',function(e){ ... });
Then, trigger the event as follows:
$(#myelement).trigger('customEventName');
Alternatively, you can add additional parameters for custom events, as shown in the following example:
$(#myelement).bind('customEventName',function(e,data){ if(data.custom) ... });$(#myelement).trigger('customEventName',{ custom: false });
Magic update
The so-called magic upgrade is actually to enable all the custom events of the entire program to be automatically registered and bound to jQuery. Then, when executed, all the modules that register the event will execute. For example, the module User. the UserUpdate method and Blogs defined in js. the BlogUpdate method defined in js defines the function to be executed when a blog is published. Throughout the process, we can register a unified event name (such as BlogAdded) bind to a container specified by jQuery (such as document), and then execute $ (document) after the blog is published successfully ). trigger (BlodAdded) is OK.
Below is a general sample code:
var components = [User, Blog, Group, Friend, Topic, Photo]; var eventTypes = [AddComplete, UpdateComplete, DeleteComplete, LockComplete, UnLockComplete]; $.each(components, function(i,component) { $.each(eventTypes, function(i,eventType) { var handler = component[eventType]; if (handler) $(document).bind(eventType, handler); }); })
Then, the Code defined by each js module is installed in the following format:
User= { AddComplete: function(e, data) { //... }, UpdateComplete: function(e, data) { //... } }
In this way, we can use jQuery to trigger our events wherever we need them:
$(document).trigger(UpdateComplete, data);
Using this method, you can find that the method of a module can only register one event. If you register multiple event triggers using one method, you can use the following method:
var blogController = { blogAddOrUpdateComplete: function() { //... } } blogController.blogAddComplete = blogController.blogUpdateComplete = blogController.blogAddOrUpdateComplete;
Last Note: This article only shows a simple example. Do not mix the usage of the same event name of different modules, for example, User. addComplete and Blog in js. the AddComplete in js may have no relationship at all, that is to say, it only processes its own logic. At this time, this event should not be handled in a unified manner, but if the content to be detected is the same, this can be used. For example, DisableUserComplete can be used for general purposes. Because the User module needs to process operations after the account is disabled, the Blog module may also need to process operations after the account is disabled.