In-depth understanding of the JavaScript series (31): Explanation of the proxy mode in the design mode _ javascript skills

Source: Internet
Author: User
This article mainly introduces the JavaScript series (31): detailed explanation of the proxy mode of the design mode. The proxy mode allows the proxy object to control the reference of a specific object. The proxy can be almost any object: file, resources, objects in memory, or something that is hard to copy. For more information, see 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?

The Code is as follows:


// Declare the beauty object first
Var girl = function (name ){
This. name = name;
};

// This is dudu
Var dudu = function (girl ){
This. girl = girl;
This. sendGift = function (gift ){
Alert ("Hi" + girl. name + ", dudu gives you a gift:" + gift );
}
};

// Uncle is a proxy
Var proxyTom = function (girl ){
This. girl = girl;
This. sendGift = function (gift ){
(New dudu (girl). sendGift (gift); // send flowers to dudu
}
};

The call method is very simple:

The Code is as follows:


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:

The Code is as follows:


Dave donews vids

Select All/reselect



  1. Gravedigger

  2. Save Me

  3. Crush

  4. Don't Drink The Water

  5. Funny the Way It Is

  6. What wocould You Say


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:

The Code is as follows:


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:

The Code 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:

The Code is as follows:


Var proxy = {
Ids: [],
Delay: 50,
Timeout: null,
Callback: null,
Context: null,
// Set the Request id and callback to trigger the callback during playback.
MakeRequest: function (id, callback, context ){

// Add to 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 use the proxy to call http. makeRequest
Flush: function (){
// Proxy. handler is the callback for yahoo requests
Http. makeRequest (this. ids, 'proxy. handler ');
// After the data is requested, execute the proxy. handler method (there is another set callback)

// Clear the timeout and queue
This. timeout = null;
This. ids = [];

},
Handler: function (data ){
Var I, max;

// Call the callback of a single video
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:

The Code is as follows:


Var videos = {
// Initialize the player code and start playing
GetPlayer: function (id ){
Return ''+
''+
''+
''+
''+
''Height = "255" '+
& Apos; width = "400" & apos; +
'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 + '& eID = 1301797 & lang = us & ympsc = 4195329 & enableFullScreen = 1 & shareEnable = 1"' +
'\/>' +
'<\/Object> ';
},
// Display the spliced information, and then display it in the append to the bottom of li
UpdateList: function (data ){
Var id,
Html = '',
Info;

If (data. query ){
Data = data. query. results. Video;
}
Id = data. id;
Html + = '';
Html + = ''+ data. title + '<\/h2> ';
Html + ='

'+ Data. copyrightYear +', '+ data. label +' <\/p> ';
If (data. Album ){
Html + ='

Album: '+ data. Album. Release. title +', '+ data. Album. Release. releaseYear +'
';
}
Html + ='

» Play <\/a> <\/p> ';
Info = document. createElement ('P ');
Info. id = "info" + id;
Info. innerHTML = html;
$ ('V' + id). appendChild (info );
},
// Obtain and display information
GetInfo: function (id ){
Var info = $ ('info' + id );

If (! Info ){
Proxy. makeRequest (id, videos. updateList, videos); // executes proxy duties and passes in the videos. updateList callback function
Return;
}

If (info. style. display = "none "){
Info. style. display = '';
} Else {
Info. style. display = 'none ';
}
}
};

Now we can process the Click Event code. Because there are many a connections, if each connection is bound to an event, it is clear that the performance will be faulty, So we bind the event

    Element, and then check whether the clicked connection is a. If it indicates that the video address is clicked, then you can play the video:

    The Code is as follows:


    $ ('Vids '). onclick = function (e ){
    Var src, id;

    E = e | window. event;
    Src = e.tar get | e. srcElement;

    // If it is not a connection, it will not be processed.
    If (src. nodeName. toUpperCase ()! = ""){
    Return;
    }
    // Stop bubbling
    If (typeof e. preventDefault = "function "){
    E. preventDefault ();
    }
    E. returnValue = false;

    Id = src. href. split ('--') [1];

    // If you click the connection to play in the produced video information area, start playing.
    // 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:

    The Code is as follows:


    $ ('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 the play connection
    If (hrefs [I]. className = "play "){
    Continue;
    }
    // Ignore unselected items
    If (! Hrefs [I]. parentNode. firstChild. checked ){
    Continue;
    }

    Id = hrefs [I]. href. split ('--') [1];
    Hrefs [I]. parentNode. id = "v" + id;
    Videos. getInfo (id );
    }
    };

    Summary

    The proxy mode is generally applicable to the following scenarios:

    1. remote proxy is used to provide local representation of an object in different address spaces. In this way, the fact that an object exists in different address spaces can be hidden, just like the proxy class in web service.
    2. virtual Proxy: Creates objects with high overhead as needed 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. The security proxy is used to control the access permissions of real objects. It is generally used for objects with different access permissions.
    4. Intelligent Guidance: the proxy handles other things only 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

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.