Using the on and off methods to write efficient JS code

Source: Internet
Author: User

First of all, the cause of this topic: Recently discovered the company's function code, many after the DOM object is deleted, its declaration of binding on the window Resize event also persists, resulting in the same function code executed several times. It's a big hole for someone like me who's a minor code freak.

So, here's an example of jquery's resize approach, which explains what I understand as an efficient notation.

Let's look at the normal Bind Resize event under window:

1 $ (window). Resize (function() {2     console.log ("hehe"); 3 }); 4 $ (window). Resize (function() {5     console.log ("Hehe2"); 6 });

The execution results after several resize have been triggered as follows:

Two event handlers do not overwrite each other because the jquery approach is DOM2-level (not in detail here). The problem here is that if you delete the DOM object, its unique, non-binding response method does not have to be deleted, it will accumulate, like ghosts. And here is the so-called impact performance, so that the browser valuable CPU is invalid function code consumption, the user experience also accumulated a certain number of levels of the ghost code, gradually reduced, or even stuck.

How to solve it? Kill it, of course!

If you use the Unbind method, you can clear the operation, but the key is sometimes not deleted, especially the team of multi-person collaboration. So, the on and off methods come in handy!

Transform the Resize method:

1 function () {2     console.log ("hehe"); 3 }); 4 function () {5     console.log ("Hehe2"); 6 });

The focus is on the first parameter of the on method: Resize.fn1. The solid point is the Resize method that the Window object is bound to, and the solid point is followed by an alias for the method that identifies the method (note that there can be no spaces, which one of my colleagues encountered).

This alias, which is used to call the off method, deletes the specified corresponding handler.

If I want to delete the output "hehe" handler, the code is as follows:

1 $ (window). Off ("resize.fn1");

In this way, you can precisely destroy the unwanted function code without causing it to be deleted.

Another reminder is that the resize event can write n as needed, and then you can identify the same alias for the same lifetime code according to the function of the business, so that it can be destroyed uniformly.

Expand your thinking:

In general, we write functions that are more scalable, such as creating a mask, and generally reserving a Calbackl method, as follows:

1 functionOverlay (options) {2   var default= {3   /*Other Parameters*/4Callbackfalse                  5     }; 6   varSettings = $.extend ({},default, options);7   if(!!settings.callback) {8 Settings.callback (); 9     }    Ten}

However, we can do a better job of extensibility, for example, when the mask initialization is generated, a resize event is bound to the window, and the output of 1

1 vardata = {2     /*Other Parameters*/3 EXTFN: [{4 obj:$ (window),5Name: "Resize.overlay", 6Fn:function(){7Console.log (1);8                 }9                }]Ten }; One  A overlay (data); -  - functionOverlay (options) { the   var default= { -     /*Other Parameters*/   -Callbackfalse, - extfn:[] +   };  -   varSettings = $.extend ({},default, options); +  A   if(Settins.extFn.length > 0){ at     varextfn_obj, Extfn_name, EXTFN_FN; -    -      for(vari = 0, len = settings.extFn.length; i < Len; i++){ -Extfn_obj =settings.extfn[i].obj; -Extfn_name =Settings.extfn[i].name; -EXTFN_FN =Settings.extfn[i].fn; inExtfn_obj.off (Extfn_name);//destroying the old event bindings -Extfn_obj.on (Extfn_name, EXTFN_FN);//Add a new event binding to     }   +   }   -    the   /*other methods and callback*/   *}

Of course, when you destroy the build mask, you should also destroy the custom binding extension method, here is not the DAO ~

Using the on and off methods to write efficient JS code

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.