In-depth understanding of JavaScript series (31): Proxy mode for design patterns

Source: Internet
Author: User

Introduction Agent, as the name implies is to help others work, GOF the proxy mode is defined as follows: Proxy mode, for other objects to provide a proxy to control access to this object. The proxy mode enables the proxy object to control references to specific objects. Proxies can be almost any object: files, resources, objects in memory, or things that are difficult to replicate. The text we come to give a simple example, if Dudu to send yogurt sister roses, but do not know her contact or embarrassed, want to entrust uncle to send these roses, that Uncle is an agent (actually very good, can buckle a few roses to daughter-in-law), then how do we do? //Declare the Beauty object firstvarGirl =function(name) { This. Name =name;};//this is Dudu .varDudu =function(girl) { This. Girl =girl;  This. Sendgift =function(gift) {alert ("Hi" + Girl.name + ", Dudu send you a gift:" +gift); }};//Uncle is the agentvarProxytom =function(girl) { This. Girl =girl;  This. Sendgift =function(gift) {(NewDudu (Girl)). Sendgift (gift);//Send flowers for Dudu .}}; The invocation method is very simple:varProxy =NewProxytom (NewGirl ("Yogurt Little Sister"));p Roxy.sendgift ("999 Roses"); One through the above code, I believe that the agent mode has been very clear, we come to the actual situation: we have a simple playlist, you need to click on a single connection (or select all) when the connection below the link to display the video description and the play button, Click the Play button to play the video, the list structure is as follows:T Drink the water</a></li> <li><input type= "checkbox" checked><a href= "/http/ new.music.yahoo.com/videos/--217241800 ">funny the It is</a></li> <li><input type=" CheckBox "Checked><a href=" http://new.music.yahoo.com/videos/--2144532 ">what would you say</a></ Li></ol> We first analyze the following, first of all we have to monitor not only a connection click events, but also to monitor the "Select/reverse" click events, and then request the server to query the video information, assembled HTML information displayed in the last position of the LI element, The effect is as follows: Then monitor the play connection's Click event and click to start playing later, the effect is as follows: OK, start, no jquery, we customize a selector: var $ = function (ID) {return document.getElementById ( ID);}; Since Yahoo's JSON service provides the callback parameter, we pass in our custom callback to accept the data, the concrete query string assembly 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:varProxy ={ids: [], Delay:50, timeout:NULL, Callback:NULL, Context:NULL,    //set the ID and callback of the request to trigger callbacks when playingMakeRequest: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); }    },    //triggers the request and invokes the http.makerequest using the proxy responsibilityFlushfunction () {        //Proxy.handler for callback when requesting Yahoo.Http.makerequest ( This. IDs, ' Proxy.handler '); //after requesting the data, execute the Proxy.handler method immediately after (there is another setting in the callback)                //Clear timeout and queue         This. Timeout =NULL;  This. ids = []; }, Handler:function(data) {varI, Max; //callback invocation of a single video        if(parseint (Data.query.count, 10) = = = 1) {Proxy.callback.call (Proxy.context, Data.query.results.Video); return; }        //callback calls to 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 has 3 seed functions: Get information, display information, play Video:varVideos = {    //Initialize the player code and start playingGetplayer:function(ID) {return"+ ' <object width=" 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;shareenable=1 ' \/> ' + ' &L T;param name= "wmode" value= "Transparent" \/> ' + ' <embed ' + ' height= "255" ' + ' width = "+" ' + ' 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 "' + ' \/& gt; ' + ' <\/object> '; },    //The stitching information is displayed and then displayed in the bottom of the append to LiUpdatelist:function(data) {varID, HTML= ' ', info; if(data.query) {data=Data.query.results.Video; } ID=data.id; HTML+ = ' ; HTML+ = ' ; HTML+ = ' <p> ' + data.copyrightyear + ', ' + Data.label + ' <\/p> '; if(data. Album) {HTML+ = ' <p>album: ' + data. Album.Release.title + ', ' + data. Album.Release.releaseYear + ' <br \/> '; } HTML+ = ' <p><a class= "Play" href= "http://new.music.yahoo.com/videos/--' + ID + '" >&raquo; Play<\/a><\/p> '; Info= document.createelement (' div '); Info.id= "Info" +ID; Info.innerhtml=html; $(' V ' +ID). appendchild (info); },    //get information and showGetInfo:function(ID) {varInfo = $ (' info ' +ID); if(!info) {proxy.makerequest (ID, videos.updatelist, videos);//perform agent duties and pass in the videos.updatelist callback function            return; }        if(Info.style.display = = = "None") {Info.style.display= ' '; } Else{Info.style.display= ' None '; }}; Now you can handle the code of the Click event, because there are many a connections, if each connection is bound to an event, there is obviously a performance problem, so we bind the event to<ol>element, and then detects if the click is a connection, if it means that we clicked on the video address, then it can be played: $ (' Vids '). onclick =function(e) {varsrc, id; E= e | |window.event; SRC= E.target | |e.srcelement; //if it's not connected, it's not going to work.    if(Src.nodeName.toUpperCase ()!== "A") {        return; }    //Stop bubbling    if(typeofE.preventdefault = = = "function") {e.preventdefault (); } e.returnvalue=false; ID= Src.href.split ('---') [1]; //If you click Connect Play on the video information area that is already produced, start playing    //and then return doesn't go on.    if(Src.classname = = = "Play") {Src.parentNode.innerHTML=Videos.getplayer (ID); return; } src.parentNode.id= "V" +ID; Videos.getinfo (ID); //This is the first time to click on the display of video information processing codethe selection of the inverse of the code is similar, we do not explain: $ (' Toggle-all '). onclick =function(e) {varHREFs, 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 items that are not selected        if(!hrefs[i].parentnode.firstchild.checked) {            Continue; } ID= Hrefs[i].href.split ('---') [1]; Hrefs[i].parentnode.id= "V" +ID;    Videos.getinfo (ID); }}; Full code: https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/proxy.htmlSummary proxy mode generally applies to the following situations: remote agents, that is, for an object to provide local representation in different address spaces, so that you can hide the fact that an object exists in a different address space, just like a proxy class in a Web service. Virtual agent, according to the need to create a very expensive object, through it to hold the instantiation of the real object that takes a long time, such as the browser rendering the first display of the problem, and the picture can be slowly displayed (that is, the virtual agent to replace the real picture, the virtual agent saved the real picture path and size. A security agent that controls access to real objects, typically for objects that have different access rights. Smart guidance, when invoking real objects, the agent handles something else. For example, in C # garbage collection, the use of objects will have a reference number, if the object is not referenced, the GC can be recycled it. Reference: "Big Talk design mode" synchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing. 

In-depth understanding of JavaScript series (31): Proxy mode for design patterns

Related Article

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.