Use AOP to improve javascript code

Source: Internet
Author: User
Aop is also called Aspect-Oriented Programming. Those who have used spring must be very familiar with it. In js, AOP is a technical point that has been seriously ignored, this article uses the following small examples to illustrate the use of AOP in js.

Aop is also called Aspect-Oriented Programming. Those who have used spring must be very familiar with it. In js, AOP is a technical point that has been seriously ignored, this article uses the following small examples to illustrate the use of AOP in js.

1. Prevent window. onload from being overwritten twice.
2. No intrusive statistical code.
3. Separate Form requests and verification.
4. Add parameters to the ajax request dynamically.
5. responsibility chain mode.
6. Combination instead of inheritance.

The before and after functions are provided first. as the name implies, a function is executed before or after another function. However, before or after can be used to share this and arguments with the current function, in this way, there will be more places for us to play.

Processing window. onload is overwritten twice.

Some time ago I saw a personal question in the QQ group. I had to rewrite window. onload so that I could not overwrite the previous window. onload function.

The most primitive solution is to add your new Code directly to the original window. onload.

The disadvantage is obvious. modifying the original function is the most invasive method.

Another better solution is to use the intermediate variable to save the previous window. onload;

In this way, it also takes some extra cost to manage an annoying intermediate Variable _ onload.

Imagine this scenario. When people feel that the weather is cold, they naturally choose to wear a mink coat when they go out, rather than replacing their skins with mink. the benefits of dynamic decoration are embodied, and they will not intrude into the previous functions.

Non-invasive Statistical Code

Statistics Code that is not related to the logic should be hard inserted into the function. I believe many people who have reported the code are uncomfortable. for example, the following code is used to calculate how long a function that creates 1000 nodes takes on your computer.

With the aop method, you no longer need to make changes within the function. First, define a general package.

With only one line of code, you can add the time statistics function to any function.

Separate Form requests and Verification

We often perform some verification before submitting a form to determine whether the form should be submitted normally. The worst way is to put the verification logic in the send function.

The better way is to put all validation rules in a set in the Policy mode, and return false or true to determine whether verification is successful. In this way, you can select and replace the validation rules at will.

There is another drawback. The Checksum and send requests are coupled to a function. We use aop to separate them and make validata a plug-in for real plug-and-play. you only need to change the send function:

Before Function. prototype. before code is not hard to see. We agree that if the current function returns false, it will block the execution of the next function. Therefore, when validata returns false, it will no longer execute send. because the previously mentioned before function can share this and arguments with the current function, the value parameter can also be smoothly transmitted to the validata function.

Dynamically add parameters to ajax requests

In the first example, window. onload uses the after decoration. Here the before front decoration is used. Some parameters are dynamically added before ajax requests.

We have encountered many cross-origin requests. jsonp and iframe are both common methods. previously, in our project, the retype = jsonp parameter represents a jsonp request, and the retype = iframe parameter represents an iframe request. there is no difference in the parameters of these two requests. you can use before to dynamically describe the retype parameter.

First define a proxy function for ajax requests.

This function does not contain logic processing and branch statements. It does not care whether it is a jsonp request or an iframe request. It is only responsible for sending data. It is a good function with a single responsibility.

Next, place a before decorator before sending the request.

Start sending request:

Responsibility chain mode.

The typical application scenario of the responsibility chain mode in js is event bubbling. connect all child nodes and parent nodes to a chain and pass events along the chain until a node can process the events. the responsibility chain mode is an artifact that eliminates too many if else statements.

Taking a recent requirement as an example, there is a file upload function that provides the control, html5, flash, and form upload methods. determine the current upload mode based on their priorities and browser support. before I perform the transformation, its pseudocode is like this:

Of course, the actual code is far more than that, including various control initialization and fault tolerance. One day I needed to block the flash. It seemed very simple, but the difficulty was similar to removing a wool vascular beside the heart.

If you try the responsibility chain model, you can see how simple things will be:

The first step is to rewrite the previous after function so that when an object is returned, the transfer of the responsibility chain is blocked, and when null is returned, the request is continuously transmitted.

Next, we will wrap the creation methods of each control in their respective functions to ensure that there is no logic crossover or mutual pollution.

Finally, use the responsibility chain to link them up:

It is foreseeable that I need to block flash again one day. At that time, I only need to change this line of code:

Combination instead of Inheritance

Most of the time, when designing a program, we will encounter the problem of combination or inheritance. In general, the combination is more flexible and lightweight. Let's take the previous file upload as an example.

I defined a superclass Upload and derived four subclasses.
Plugin_Upload, Html5_Upload, Flash_Upload, and Form_Upload.

Plugin_Upload will inherit the parent class, get most of the Upload functions, and then customize some features of the control Upload. for example, the other three upload Methods start to upload files after selecting files. the upload of the control will undergo a round of file scanning before the upload starts.

First, Plugin_Upload inherits the Upload and then overwrites its start_upload method.

With a lighter combination method, you can directly decorate the scanning function for the original start_upload function, and do not even need to derive an additional subclass.

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.