A deep understanding of the JavaScript series (31): the proxy mode of the design mode, and a deep understanding of javascript

Source: Internet
Author: User

A deep understanding of the JavaScript series (31): the proxy mode of the design mode, and a deep understanding of javascript
Introduction

Proxy, as its name implies, is to help others do things. The GoF defines the proxy mode as follows:

Proxy mode, which provides a Proxy for other objects to control access to this object.

The proxy mode allows the proxy object to control the reference of a specific object. A proxy can be almost any object: objects, resources, objects in memory, or something that is hard to copy.

Body

Let's take a simple example. If dudu wants to send the yogurt girl's Rose, but does not know her contact information or is embarrassed, he wants to entrust his uncle to send the roses, so Uncle is an agent (in fact, it is quite good, you can deduct a few to the daughter-in-law), then how do we do it?

// Declare the beauty object var girl = function (name) {this. name = name ;}; // this is duduvar dudu = function (girl) {this. girl = girl; this. sendGift = function (gift) {alert ("Hi" + girl. name + ", dudu gives you a gift:" + gift) ;}}; // uncle is the proxy var proxyTom = function (girl) {this. girl = girl; this. sendGift = function (gift) {(new dudu (girl )). sendGift (gift); // send flowers for dudu }};

The call method is very simple:

Var proxy = new proxyTom (new girl ("yogurt girl"); proxy. sendGift ("999 roses ");
Practice

Through the above code, I believe you are very clear about the proxy mode. In actual practice, we have a simple playlist and need to click a single connection (or select all) the video description and play button are displayed at the bottom of the connection, and the video is played when the play button is clicked. The list structure is as follows:

<H1> Dave donews vids 

First, we will analyze the following. First, we will not only monitor the click events of connection a, but also the click events of "select all/reselect", and then request the server to query the video information, the assembled HTML information is displayed at the last position of the li element. The effect is as follows:

Then, monitor the Click Event of the play connection and click it to start playing. The effect is as follows:

Okay. At first, there is no jQuery. We can customize a selector:

var $ = function (id) {    return document.getElementById(id);};

Because the Yahoo json Service provides the callback parameter, we pass in our custom callback to accept data. The assembled code for the specific query string is as follows:

var http = {    makeRequest: function (ids, callback) {        var url = 'http://query.yahooapis.com/v1/public/yql?q=',            sql = 'select * from music.video.id where ids IN ("%ID%")',            format = "format=json",            handler = "callback=" + callback,            script = document.createElement('script');            sql = sql.replace('%ID%', ids.join('","'));            sql = encodeURIComponent(sql);            url += sql + '&' + format + '&' + handler;            script.src = url;        document.body.appendChild(script);    }};

The proxy object is as follows:

Var proxy = {ids: [], delay: 50, timeout: null, callback: null, context: null, // set the Request id and callback so that the callback makeRequest: function (id, callback, context) is triggered during playback {// Add it to the queue dd to the queue this. ids. push (id); this. callback = callback; this. context = context; // set timeout if (! This. timeout) {this. timeout = setTimeout (function () {proxy. flush () ;}, this. delay) ;}}, // trigger the request and call http by proxy. makeRequest flush: function () {// proxy. handler is the callback http when requesting yahoo. makeRequest (this. ids, 'proxy. handler'); // after the data is requested, the proxy is executed. handler method (which has another set callback) // clear the timeout and queue this. timeout = null; this. ids = [] ;}, handler: function (data) {var I, max; // callback of a single video calls if (parseInt (data. query. count, 10) = 1) {proxy. callback. call (proxy. context, data. query. results. video); return;} // call the callback of multiple videos for (I = 0, max = data. query. results. video. length; I <max; I + = 1) {proxy. callback. call (proxy. context, data. query. results. video [I]) ;}}};

The video processing module provides the following functions: getting information, displaying information, and playing videos:

Var videos = {// initialize the player code and start playing getPlayer: function (id) {return ''+ '<object width =" 400 "height =" 255 "id =" uvp_fop "allowFullScreen =" true ">' + '<param name =" movie "value = "http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf" \/> '+' <param name = "flashVars" value = "id = V' + id + '& amp; eID = 1301797 & amp; lang = us & amp; enableFullScreen = 0 & amp; extends enable = 1 "\/> '+' <param name =" wmode "value =" transparent "\/> '+' <e Mbed '+ 'height = "255"' + 'width = "400" '+ 'id = "uvp_fop"' + 'allowfullscreen = "true" '+ 'src = "http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf "'+ 'Type =" application/x-shockwave-flash "' + 'flashvars =" id = V' + id + '& amp; eID = 1301797 & amp; lang = us & amp; ympsc = 4195329 & amp; enableFullScreen = 1 & amp; shareEnable = 1 "'+' \/> '+' <\/object> ';}, // splice information to display the content, and then display updateList at the bottom of append to li: function (data) {var I D, html = '', info; if (data. query) {data = data. query. results. video;} id = data. id; html + = ''; html + = '

Now we can process the code for click events. Because there are many a connections, if each connection is bound to an event, it is obvious that there will be performance problems, so we bind the event to the <ol> element, then, check whether a connection is clicked. If yes, it indicates that the video address is clicked, and then you can play the video:

$ ('Vids '). onclick = function (e) {var src, id; e = e | window. event; src = e.tar get | e. srcElement; // The if (src. nodeName. toUpperCase ()! = "A") {return;} // stop bubbling if (typeof e. preventDefault = "function") {e. preventDefault ();} e. returnValue = false; id = src. href. split ('--') [1]; // if you click the connection play of the produced video information area, start playing the video. // then return does not continue if (src. className = "play") {src. parentNode. innerHTML = videos. getPlayer (id); return;} src. parentNode. id = "v" + id; videos. getInfo (id); // This is the processing code for displaying the video information when you click it for the first time };

The code for Selecting All invert selections is similar, so we will not explain it:

$ ('Toggle-all '). onclick = function (e) {var hrefs, I, max, id; hrefs = $ ('vids '). getElementsByTagName ('A'); for (I = 0, max = hrefs. length; I <max; I + = 1) {// ignore play connection if (hrefs [I]. className = "play") {continue;} // ignore if (! Hrefs [I]. parentNode. firstChild. checked) {continue;} id = hrefs [I]. href. split ('--') [1]; hrefs [I]. parentNode. id = "v" + id; videos. getInfo (id );}};

Full: https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/proxy.html

Summary

The proxy mode is generally applicable to the following scenarios:

  1. Remote proxyThat is, to provide a local representation of an object in different address spaces, this can hide the fact that an object exists in different address spaces, just like the proxy class in web service.
  2. Virtual proxyCreate objects with high overhead as needed, and use them to store real objects that take a long time for instantiation. For example, the problem is first displayed during browser rendering, the image can be displayed slowly (that is, the real image is replaced by a virtual proxy, and the virtual proxy saves the path and size of the real image.
  3. Security ProxyUsed to control the access permissions of real objects. Generally, the object should have different access permissions.
  4. Smart GuideThe proxy only handles other things when calling real objects. For example, garbage collection in C # can be referenced multiple times when an object is used. If the object is not referenced, GC can recycle it.
    Reference: big talk Design Model

Copyright statement: This article is the original author of the http://www.zuiniusn.com, not allowed by the blogger can not be reproduced.

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.