Improving JavaScript code with AOP

Source: Internet
Author: User

AOP is also called aspect-oriented programming, with spring students must be very familiar with it, and in JS, AOP is a seriously neglected technical point, this article through the following few small examples, to say that the use of AOP in JS Magic.

1, prevent window.onload from being covered by two times.

2, no intrusive statistical code.

3, separate form requests and checksums.

4. Dynamically add parameters to the AJAX request.

5, responsibility chain mode.

6, combination instead of inheritance.

The 2 "tangent" functions of before and after are given first. As the name implies, let a function be executed before or after another function, and subtly, these 2 functions can be common to this and arguments, so that we have a lot of places to play.

Processing window.onload is covered two times.

Some time ago to see the QQ group has a person to ask questions, to rewrite window.onload, how can not put the previous window.onload function cover out.

The original solution must be to add your new code directly to the original window.onload.

Such a disadvantage is very obvious, need to change the original function, is the most intrusive one of the practices.

Another slightly better solution is to save the previous window.onload with intermediate variables;

In this way, more than a nasty middle variable __onload, to manage it also takes some extra cost.

Imagine this scene, when people feel the weather is cold, go out of the natural choice to wear a mink coat, rather than rip off their skins for mink. The benefits of dynamic decoration are reflected in the function that is not invaded at all.

Non-intrusive statistical code

The statistical code that has nothing to do with logic has to be stuck in the function, which I believe many of the students who have reported are very upset. The following code, for example, is used to count how much time is spent on a user's computer to create a 1000-node function.

In an AOP way, you no longer need to make changes inside a function, defining a generic wrapper first.

As long as one line of code, can give any function to add statistical time function.

Detach form Request and checksum

We often do some validation before submitting the form to determine whether the form should be submitted properly. The worst thing to do is put the validation logic in the Send function.

The better way is to put all the validation rules in a set with the policy mode, return False or True to determine whether to pass the validation. This allows you to arbitrarily select and replace the calibration rules.

This also has a disadvantage, the checksum sends the request to the 2 request coupling to a function inside, we use AOP to separate them, the validata into the plug-in, the real Plug and play. Simply change the Send function to:

It is not difficult to see through the first Function.prototype.before code, we agreed that the current function returns false, it will block the execution of the next function, so when Validata returns false, it will not continue to execute send.

Adding parameters to an AJAX request dynamically

In the first example, Window.onload is used after the post-decoration, which is decorated with before front-facing. Add some parameters dynamically before the AJAX request.

We have encountered many cross-domain requests, both JSONP and IFRAME are common ways. Previously in our project, the parameter Retype=jsonp represents the JSONP request, and the retype=iframe represents an IFRAME request. In addition to the parameters of these 2 requests there is no difference. Then you can use before to decorate the retype parameters dynamically.

Define a proxy function for an AJAX request first.

This function has no logical processing and branching statements, nor does it care whether it is a JSONP request or an IFRAME request. It is only responsible for sending data and is a good function of a single duty.

Next, place a before adorner before sending the request.

To start sending a request:

Responsibility chain mode.

The typical application scenario of the responsibility chain mode in JS is event bubbling. Link all child nodes and parent nodes together and pass events along this chain until one node can handle it. The responsibility chain pattern is an artifact that eliminates excessive if else statements.

Take a recent need to do an example, there is a file upload function, provides the control, HTML5, Flash, form upload these 4 ways to upload. Determine which upload method is currently supported based on their priority and browser support. Before I do the transformation, it's pseudo-code is probably like this:

Of course, the actual code is far more than that, including the various control initialization, fault tolerance and so on. One day I need to block out the Flash control, which seems to be a very simple requirement, but the difficulty is actually similar to tearing down a wool vein next to the heart.

If you try the chain of responsibility model, see how simple things can become:

The first step is to rewrite the previous after function so that when an object is returned, the delivery of the responsibility chain is blocked, and the request continues to be passed when NULL is returned.

Next, each type of control is created in its own function, ensuring that there are no logical intersections and contamination.

Finally string them up with a chain of responsibilities:

Predictably, one day I need to block out flash, then I just need to change this line of code. Change to:

Combination instead of inheritance

Many times when we are designing a program, we encounter problems with the use of combinations or inheritance. In general, using a combination is more flexible and lightweight. Or take an example from the previous document.

I have defined a superclass upload, which derives 4 subclasses of the class.

Plugin_upload, Html5_upload, Flash_upload and Form_upload.

Plugin_upload inherits the parent class, gets most of the functionality of the upload, and then customizes some of the features uploaded by the control. For example, the other 3 ways to upload is to select files and then start uploading. A control upload passes through a scan of the file before it starts uploading.

The first approach is to plugin_upload inherit upload and then rewrite its Start_upload method.

With a lighter combination, the original Start_upload function can be directly decorated with scanning functions, even without the need to derive an additional subclass.

Some students do not like to extend the function of the prototype, the alternative is to add a parameter to before and after, or as jquery and underscore as a layer of packaging.

Improving JavaScript code with AOP

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.