Deep understanding of the JavaScript series (31): Design mode of the agent mode of detailed _javascript skills

Source: Internet
Author: User
Tags flush

Introduced

Agent, as the name implies is to help others to do things, gof the agent mode is defined as follows:

Agent mode (proxy), which provides a proxy for other objects to control access to this object.

The proxy mode makes the proxy object control the reference to the specific object. Proxies can be almost any object: files, resources, objects in memory, or something that is hard to replicate.

Body

Let's give a simple example, if Dudu to send yogurt sister roses, but do not know her contact method or embarrassed, want to entrust uncle to send these roses, that Uncle is an agent (in fact very good, can buckle a few flowers to daughter-in-law), then how do we do?

Copy Code code as follows:

Make a declaration of a beautiful 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 send you a gift:" + gift);
}
};

Mister is an agent
var proxytom = function (girl) {
This.girl = Girl;
This.sendgift = function (gift) {
(New Dudu (Girl)). Sendgift (gift); Send flowers for Dudu.
}
};

The invocation method is very simple:

Copy Code code as follows:

var proxy = new Proxytom (New Girl ("Yogurt Sister"));
Proxy.sendgift ("999 Roses");

A piece of real combat

Through the code above, I believe that the agent model has been very clear, we come to the actual combat: We have a simple playlist, you need to click on a single connection (or select all) when the link below the display video song introduction as well as Play button, click the Plays button when playing video, list structure as follows:

Copy Code code as follows:

<p><span id= "Toggle-all" > all Select/Reverse Selection </span></p>
<ol id= "Vids" >
<li><input type= "checkbox" Checked><a href= "http://new.music.yahoo.com/videos/--2158073" > Gravedigger</a></li>
<li><input type= "checkbox" Checked><a href= "http://new.music.yahoo.com/videos/--4472739" >save Me </a></li>
<li><input type= "checkbox" Checked><a href= "http://new.music.yahoo.com/videos/--45286339" >crush </a></li>
<li><input type= "checkbox" Checked><a href= "http://new.music.yahoo.com/videos/--2144530" >don ' t Drink the Water</a></li>
<li><input type= "checkbox" Checked><a href= "http://new.music.yahoo.com/videos/--217241800" > Funny the Way 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 should not only monitor the A-link click events, but also monitor the "Select/reverse" click events, and then request the server to query the video information, assembly of HTML information displayed in the last position of Li elements, the effect is as follows:

And then monitor the play connected to the click of the event, click to start playing later, the effect is as follows:

Okay, start, no jquery, we're customizing a selector:

Copy Code code as follows:

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

Since Yahoo's JSON service provided callback parameters, we passed in our custom callback to accept the data, and the query string assembly code is as follows:
Copy Code code 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 objects are as follows:

Copy Code code as follows:

var proxy = {
IDS: [],
DELAY:50,
Timeout:null,
Callback:null,
Context:null,
Set the ID and callback of the request to trigger the callback when playing
Makerequest:function (ID, callback, context) {

Adding to queues 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 with the proxy responsibility
Flush:function () {
Proxy.handler to request the Yahoo time callback
Http.makerequest (this.ids, ' Proxy.handler ');
After the data is requested, the Proxy.handler method is executed immediately after it (callback with another setting inside)

Clear timeout and queues
This.timeout = null;
This.ids = [];

},
Handler:function (data) {
var i, Max;

Callback calls to a single video
if (parseint (Data.query.count, 10) = = 1) {
Proxy.callback.call (Proxy.context, Data.query.results.Video);
Return
}

Callback calls for 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 mainly has 3 seed functions: Obtaining information, displaying information, playing video:

Copy Code code as follows:

var videos = {
Initialize the player code and start playing
Getplayer: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 + ' &eid=1301797&lang=us&enablefullscreen=0&shareenable =1 "\/> ' +
' <param name= ' wmode ' value= ' transparent ' \/> ' +
' <embed ' +
' 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 + ' &eid=1301797&lang=us&ympsc=4195329&enablefullscreen=1&shareenable=1 ' ' +
' \/> ' +
' <\/object> ';
},
The stitching information displays the content and then displays in the bottom of the append to Li
Updatelist:function (data) {
var ID,
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 + ' ">»play<\/a><\/p& gt; ';
info = document.createelement (' div ');
info.id = "info" + ID;
info.innerhtml = html;
$ (' V ' + ID). appendchild (info);
},
Get information and display
Getinfo:function (ID) {
var info = $ (' 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 Click event code, because there are a lot of a connections, if each connection is bound to the event, obviously performance will be problematic, so we bind the event to the <ol> element, and then detect whether the click is a connection, if it is that we clicked the video address, and then we can play:

Copy Code code as follows:

$ (' vids '). onclick = function (e) {
var src, 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 (typeof E.preventdefault = = "function") {
E.preventdefault ();
}
E.returnvalue = false;

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

If you click on the connection play of the video information area that has been produced, start playing
And then return will not continue.
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 code
};

The whole selection of the reverse code is very similar and we don't explain:

Copy Code code 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 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);
}
};

Summarize

Agent mode is generally applicable to the following occasions:

1. Remote proxies, which provide local representation in different address spaces for an object, can hide the fact that an object exists in a different address space, just like a proxy class in a Web service.
2. Virtual proxies, creating expensive objects as needed, it is used to store real objects that need a long time to instantiate, such as when the browser renders the problem first, and the picture can be displayed slowly (that is, the virtual proxy replaces the real picture, at which point the virtual agent saves the path and size of the real picture).
3. Security agent, used to control the permissions of real object access, generally used for objects should have different access rights.
4. Intelligent guidance, only when the real object is invoked, the agent to deal with other things. For example, garbage collection in C #, the use of objects will have a reference times, if the object is not referenced, the GC can recycle it.

Reference: "Dahua 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.