Home > Article > Web Front-end > Improve javascript code using AOP_javascript tips
Aop is also called aspect-oriented programming. Students who have used spring must be very familiar with it. In js, AOP is a seriously ignored technical point. This article will talk about it through the following small examples. The wonderful use of AOP in js.
1, prevent window.onload from being overwritten twice.
2. Non-intrusive statistical code.
3. Separate form request and verification.
4. Dynamically add parameters to ajax requests.
5. Chain of responsibility model.
6. Composition instead of inheritance.
First give the two "aspect" functions before and after. As the name suggests, one function is executed before or after another function. The clever thing is that before or after can share this and arguments with the current function. This way there will be more places for us to play.
Handle window.onload being overwritten twice.
Some time ago, I saw someone in the QQ group asking a question about how to rewrite window.onload without overwriting the previous window.onload function.
The most original solution is definitely to add your new code directly to the original window.onload.
The disadvantages of this are very obvious. You need to modify the original function, which is the most invasive approach.
Another slightly better solution is to use an intermediate variable to save the previous window.onload;
In this way, there is an annoying intermediate variable __onload, and it will cost some extra cost to manage it.
Imagine this scene. When people feel the weather is cold, they naturally choose to put on a mink coat when going out, instead of tearing off their skin and replacing it with mink. The benefits of dynamic decoration are reflected. It will not invade the previous functions at all.
No intrusive statistics code
Statistics code that has nothing to do with the logic itself has to be hard inserted into the function. I believe many students who have reported it will be unhappy. For example, the following code is used to count a function that creates 1,000 nodes. How much time will be spent on the user's computer.
Using aop method, there is no need to make changes inside the function. First define a general wrapper.
With just one line of code, you can add the function of counting time to any function.
Separate form request and verification
We often do some verification work before submitting a form to determine whether the form should be submitted normally. The worst way to write it is to put all the verification logic in the send function.
A better way is to put all the verification rules into a set using the strategy mode, and return false or true to determine whether the verification is passed. In this way, the verification rules can be selected and replaced at will.
There is another disadvantage of this. The two requests of verification and sending are coupled into a function. We use aop to separate them and make validata into a plug-in, which is truly plug-and-play. Just Change the send function to:
It is easy to see from the front code of Function.prototype.before that we agree that if the current function returns false, it will block the execution of the next function, so when validata returns false, send will no longer continue to be executed. . And because the before function mentioned before can share this and arguments with the current function, the value parameter can also be successfully passed to the valida function.
Dynamicly add parameters to ajax requests
In the first example, window.onload uses after post-decoration, here it uses before pre-decoration. Some parameters are dynamically added before the ajax request.
We have encountered many cross-domain requests, and jsonp and iframe are both very common methods. In our previous project, we used the parameter retype=jsonp to indicate a jsonp request, and retype=iframe to indicate an iframe request. In addition, There is no difference between the parameters of these two requests. Then you can use before to dynamically decorate the retype parameter.
First define a proxy function for ajax requests.
There is no logical processing or branching statements in this function, and it does not care whether it is a jsonp request or an iframe request. It is only responsible for sending data, and is a good function with a single responsibility.
Next, place a before decorator before sending the request.
Start sending request:
Chain of responsibility model.
A typical application scenario of chain of responsibility pattern in js is event bubbling. Connect all child nodes and parent nodes into a chain, and pass the event along this chain until a node can handle it. Chain of Responsibility Patterns are a great way to eliminate excessive if else statements.
Take a recent request as an example. There is a file upload function that provides four upload methods: HTML5, flash, and form upload. Determine which one to choose based on their priorities and browser support. A way to upload. Before I modified it, its pseudocode was probably like this:
Of course, the actual code is much more than that, and it also includes various control initialization, fault tolerance, etc. One day I need to block flash. It seems like a very simple requirement, but the difficulty is actually similar to removing a wool blood vessel next to the heart.
What if you try the Chain of Responsibility model and see how simple things will become:
The first step is to rewrite the previous after function so that when an object is returned, the transfer of the chain of responsibility is blocked, and when null is returned, the request continues to be passed.
Next, wrap the creation methods of each control in their own functions to ensure there is no logical overlap and mutual contamination.
Finally connect them with the chain of responsibilities:
It can be foreseen that one day I will need to block flash again. At that time, I only need to change this line of code. Change it to:
Composition instead of inheritance
Many times when we design a program, we will encounter the problem of whether to use combination or inheritance. Generally speaking, using combination is more flexible and lightweight. Let’s take the previous file upload as an example.
I defined a super class Upload, which derived 4 subclasses.
Plugin_Upload, Html5_Upload, Flash_Upload and Form_Upload.
Plugin_Upload will inherit the parent class, get most of the functions of Upload, and then customize some features of the control upload. For example, the other three upload methods start uploading after selecting the file. But the control upload will start uploading before it starts. After a round of file scanning.
The first approach is that Plugin_Upload inherits Upload, and then rewrites its start_upload method.
Using a lighter combination method, you can directly decorate the original start_upload function with the scanning function, without even deriving an additional subclass.