Being is reasonable
There’s always something worth studying. Although I don’t know much about design patterns, I still benefit a lot from studying them.
When we learn every knowledge point, we hope to be able to instantly understand and absorb the skills we use. Of course, this varies from person to person
So no matter how, on the road of learning and research, we have never given up, do not abandon do not give up should be the front er to their own slogan, refueling, no longer long winded, directly into today’s theme
The proxy pattern
Knowing what is, of course, requires knowing why
The first thing we need to know is what is the agency model?
- It provides a substitute or placeholder for an object in order to control access to it
And then it’s everywhere in life
- The singer’s manager
- Agent of soccer star (Cristiano Ronaldo, Messi)
- A daigou for cosmetics
- Etc., etc.
It is easy to understand that when you encounter anything, you should leave it to the person who has the ability to solve it
Singers interview agents to arrange, star transfer clubs and agents to talk, buy foreign cosmetics to find a buyer to fix
Let’s take a look at some applications of proxy mode in development.
This is true in practice
The proxy implements image preloading
It is well known that when a page loads images, images take some time to load in poor network conditions, and img elements are blank for a period of time when they load directly, which is not good for the experience
Therefore, we need to use a placeholder map (such as a loading map) first, and then replace it after the actual image resource request is completed
Let’s look at the code first
let myImg = (function() {
let img = document.createElement('img');
document.body.appendChild(img);
return{// Set the real image resourcesetSrc(src) { img.src = src; }}}) (); // The proxy object proxyImglet proxyImg = (function() {
let img = new Image();
img.onload = function() {// Assign myimg.setsrc (this.src) to img; }return {
setSrc(Src) {// Set the loading map to myimg.setsrc ('https://p.ssl.qhimg.com/t0103b3b9a54ba2c6f5.gif'); img.src = src; }}}) (); proxyImg.setSrc('http://p0.so.qhimgs1.com/bdr/326__/t015b81c99692979474.jpg');
Copy the code
OK, the above code implements a technical point for image proxy preloading.
Of course, there are times when it is possible to implement img.onload without an agent. It is OK to write the img.onload code into the myImg block, so why bother creating a proxy function?
- The main function is the proxy function which is used to preload the processing, if the network speed is like lightning in the future, do you still need to preload?
- The answer is no, so we’ll have to go back to myImg to find img.onload and delete the img.onload from myImg.
- If you use a proxy function, you don’t need to do this. You don’t need to call it anymore
myImg.setSrc('http://p0.so.qhimgs1.com/bdr/326__/t015b81c99692979474.jpg'); Copy the code
Merging HTTP requests
One of the biggest overhead in Web development is network requests
For example, in the case of some synchronous file upload, if it is to click a check box to send a request, so many times, the pressure of the server will become large, as the front end can not do so server, not humane enough ah
So what to do? Do not square, according to the agent mode of development ideas should be, do not have to personally, to the agent
The implementation principle is to save the file clicked to synchronize, and then send the request after a reasonable delay (this step is put in the proxy to do).
// Synchronize file functionsfunction syncFile(id) {
const url = 'xxx.com/index.php';
axios.get(url, {
params: {
id
}
});
}
let proxySyncFile = (function() {// Cache stores ids that need to be synchronized within a period of timelet cache = [],
timer;
return function(id) { cache.push(id); // Ensure that the previous timer is not overwrittenif (timer) return;
timer = setTimeout(function() {// Send the set of ids to be synchronized to the ontology after 2 seconds syncFile(cache.join()', ')); clearTimeout(timer); timer = null; cache.length = 0; }, 2000); }}) ();Copy the code
This code completes the implementation of the proxy merge HTTP request, and now it’s time to use it
// Iterate over all the checkbox elementslet checkbox = document.getElementsByTagName('input');
for (let i = 0; i < checkbox.length; i++) {
letc = checkbox[i]; // Add the click event c.onclick = to each checkbox elementfunction() {// Trigger the proxy function if it is selected and pass in the corresponding IDif (this.checked === true) { proxySyncFile(this.id); }}; }Copy the code
The caching proxy
Caching proxies can provide temporary storage for some expensive results until the next computation
If the parameters passed in are the same as before, the result of the stored operation can be returned directly
Let’s look at the most common way to compute a product
// Compute the product chestnutfunction mult() {
console.log('Let's compute the product.');
let a = 1;
for (let i = 0, len = arguments.length; i < len; i++) {
a = a * arguments[i];
}
returna; } // Cache proxylet proxyMult = (function() {// Cache object, used to store calculation resultslet cache = {};
return function() {
const args = Array.prototype.join.call(arguments, ', '); // Iterate through the cache object to see if it has the last calculated parameterif (args in cache) {
console.log('Out of cache');
return cache[args];
}
returncache[args] = mult.apply(this, arguments); }}) (); console.log(proxyMult(2, 3)); // Start counting product 6 console.log(proxyMult(2, 3, 5, 10, 2)); // Start computing the product 600 console.log(proxyMult(2, 3, 5, 10, 2)); // Go cache 600 console.log(proxyMult(2, 10, 2)); // Start counting the product 40Copy the code
Caching is an effective way to temporarily store expensive operations, so let’s make the caching proxy more generic
Whether it’s a product or a sum we can do with a modified caching proxy, look at the code
function createProxy(fn) {
let cache = {};
return function() {
const args = Array.prototype.join.call(arguments, ', ');
if (args in cache) {
return cache[args];
}
returncache[args] = fn.apply(this, arguments); }}Copy the code
The only difference in this code is that the function can be passed in as an argument to cache the proxy for different computation functions
conclusion
The proxy pattern is still important in development and is worth writing about and practicing
The above content is not very much, compared with the previous writing greatly reduced length, but the original intention remains the same, still hope to bring you some good content to share, ha ha, thank you for watching!