First, the concept of agent mode

The proxy pattern provides a proxy or placeholder for an object to control access to it.

Official definition from JavaScript Design Patterns and Development Practices.

The proxy pattern is a very meaningful pattern, you can find many proxy pattern scenarios in life. For example, celebrities are represented by agents. If you want a star to do a commercial show, you have to contact his agent. The agent will negotiate the details of the commercial performance and the payment before handing the contract to the star to sign. Ha ha, this analogy makes the proxy pattern visually easy to understand. The key to the proxy pattern is to provide a proxy object to control access to an object when it is inconvenient or not necessary for the client to directly access it. After the proxy object does some processing of the request, it passes the request to the ontology object.

Ii. What are the common agent modes?

2.1 Remote Proxy

Remote proxy is a common proxy mode that provides a LAN representative object for objects in different address Spaces. For example, there is a national chain store, the head store want to monitor the situation of each branch, can be through the monitor, so that it can intuitively understand the store information.

2.2 Protection Agent

A protected proxy controls access to an object. Follow the example of the star agent mentioned above, in which the agent is the protection agent, the contract is negotiated before the star is not disturbed, privacy is not violated.

2.3 Virtual Proxy

Virtual proxies, which are a way to save memory, suggest that when creating objects that consume a lot of memory or work with complex objects, you defer the creation of such objects until you can use them. In Web development, image preloading is a common technique. If you directly set the SRC attribute to an IMG tag node, the position of the image will be blank for a period of time due to the large image or poor network. A common practice is to load the image asynchronously with a loading image, and then fill the image into the IMG node after the image is loaded. This scenario is suitable for using a virtual agent.

2.4 Cache Proxy

The cache proxy is easy to understand. It can provide temporary storage for some expensive operation results. On the next operation, if the parameters passed in are the same as before, the stored operation results can be directly returned without recalculation. This way, is a typical “space for time” optimization means.

Third, combine front-end application cases to deepen understanding

3.1 Event Agent

In JavaScript, we often use event proxy (also called event delegate), which belongs to the proxy mode. It mainly uses the event bubbling feature to listen for the event of the child element to the delegate parent element. This way, the listener that triggers the event only needs to be bound once on the parent div element instead of N times on the child element, greatly improving the performance of the code. The code to implement the click event broker is as follows:

// Get parent const father = document.getelementByid ('father'); // bind a listener function father. AddEventListener ('click', If (e.target.tagName == 'A'){e.preventDefault() alert(' I am ${e.target.innertext} ')} })Copy the code

3.2 Image preloading

Picture preloading, the previous introduction, the optimization method belongs to the virtual proxy mode. The reason why preloading is used is to avoid bad user experience when the network is not good or the image is too large. Implementation: first use a chrysanthemum loading. GIF image placeholder, then load the image asynchronously, and fill it into the IMG node after loading the image. The specific code is as follows:

var myImage = (function(){ var imgNode = document.createElement( 'img' ); document.body.appendChild( imgNode ); return { setSrc: function( src ){ imgNode.src = src; }}}) (); var proxyImage = (function(){ var img = new Image; img.onload = function(){ myImage.setSrc( this.src ); } return { setSrc: function( src ){ myImage.setSrc( 'file:// /C:/Users/svenzeng/Desktop/loading.gif' ); img.src = src; }}}) (); proxyImage.setSrc( 'http:// imgcache.qq.com/music/photo/k/000GGDys0yA0Nk.jpg' );Copy the code

3.3 ES6的Proxy

The ES6 Proxy we usually use can be classified as a protection Proxy in Proxy mode. Why do you say that? The Proxy intercepts operations such as reading and function invocation of the target object, and then processes the operations. It does not manipulate objects directly, but rather acts like a proxy mode. During development, we set internal properties on the object. The first character of the property name starts with an underscore, indicating that these properties should not be used externally. By combining the Proxy get and set, we can protect internal properties from external reads and writes. The specific code is as follows:

const handler = { get (target, key) { invariant(key, 'get'); return target[key]; }, set (target, key, value) { invariant(key, 'set'); target[key] = value; return true; }}; function invariant (key, action) { if (key[0] === '_') { throw new Error(`Invalid attempt to ${action} private "${key}" property`); } } const target = {}; const proxy = new Proxy(target, handler); proxy._prop // Error: Invalid attempt to get private "_prop" property proxy._prop = 'c' // Error: Invalid attempt to set private "_prop" propertyCopy the code

Four,

We believe that you have fully understood the proxy mode based on specific usage scenarios. The pattern of proxy mode is: A cannot access B directly, A needs to use A proxy helper to access B, this helper is the proxy.

This article is part of the “Gold Nuggets For Free!” Event, click to view details of the event