What is Prototype.js? (prototype tutorial sample)

Source: Internet
Author: User
Tags array object contains functions hash http request string version
js| Tutorials | Sample |prototype prototype.js what is it?
In case you haven't used a famous prototype.js, let me tell you that Prototype.js is a JavaScript class library written by Sam Stephenson. This wonderfully conceived and standard class library can help you easily build rich client pages with highly interactive web2.0 features.

If you have recently tried to use it, you probably learned that the document is not a strong point for the author. Like many developers who used this class library before, I had to dive into reading Prototype.js's source code and experimenting with its functionality. I think it's a good thing to share what I've learned after I've finished learning it.

At the same time, in this article, I will also provide an unofficial reference to the objects,classes,functions,extensions provided by this class library

As you read this document, developers familiar with Ruby will notice that some of Ruby's built-in classes are very similar to the extended implementations of this class library.

Related articles
Advanced JavaScript Guide.

A few useful functions
This class library comes with a lot of predefined objects and utility functions that are clearly designed to liberate you from some repetitive typing.

Use the $ () method
The $ () method is a handy shorthand for using the document.getElementById () method too frequently in the DOM, just like this Dom method, which returns the element of the ID that the parameter passed in.

This is better than the DOM method. You can pass in multiple IDs as arguments and $ () to return an Array object with all the required elements.

<HTML>
<HEAD>
<TITLE> Test Page </TITLE>
<script src= "Prototype-1.3.1.js" ></script>
<script>
function Test1 ()
{
var d = $ (' mydiv ');
alert (d.innerhtml);
}
function Test2 ()
{
var divs = $ (' mydiv ', ' myotherdiv ');
for (i=0; i<divs.length; i++)
{
alert (divs[i].innerhtml);
}
}
</script>
</HEAD>
<BODY>
<div id= "Mydiv" >
<p>this is a paragraph</p>
</div>
<div id= "Myotherdiv" >
<p>this is another paragraph</p>
</div>
<input type= "button" Value=test1 ><br>
<input type= "button" Value=test2 ><br>
</BODY>
</HTML> Another advantage is that this function can pass in the object ID represented in string, or pass the object itself, which is useful when creating other functions that can pass two types of arguments.

Using the $f () function
The $F () function is another big welcome shortcut key that can be used to return the value of any form input control, such as the text Box,drop-down list. This method can also be used as an argument with the element ID or element itself.

<script>
function Test3 ()
{
Alert ($F (' userName '));
}
</script>
<input type= "text" id= "UserName" value= "Joe Doe" ><br>
<input type= "button" Value=test3 ><br>
Using the $a () function
The $A () function converts a single parameter that it receives to an array object.

This method, combined with an array class that has been extended by this class library, makes it easy to convert any enumerable list to or from an array object. A recommended use is to convert the DOM Node lists into a normal array object for more efficient traversal, see the example below.

<script>
function Showoptions () {
var somenodelist = $ (' lstemployees '). getElementsByTagName (' option ');
var nodes = $A (somenodelist);
Nodes.each (function (node) {
Alert (Node.nodename + ': ' + node.innerhtml);
});
}
</script>
<select id= "Lstemployees" size= "ten" >
<option value= "5" >buchanan, steven</option>
<option value= "8" >callahan, laura</option>
<option value= "1" >davolio, nancy</option>
</select>
<input type= "button" value= "Show the Options" >

Use the $H () function
The $H () function converts some objects into a hash object that is similar to an enumerable and federated array.

<script>
function Testhash ()
{
Let ' s create the object
var a = {
First:10,
SECOND:20,
Third:30
};
Now transform it into a hash
var h = $H (a);
Alert (h.toquerystring ()); Displays:first=10&second=20&third=30
}
</script>

Using the () function
$R () is the abbreviation for new Objectrange (Lowbound,upperbound,excludebounds).

Skip to the Objectrange class document to see a complete description of this class. At this point, let's take a look at an example to show how the abbreviation can be substituted. Other relevant knowledge can be found in the enumerable object documentation.

<script>
function Demodollar_r () {
var range = $R (A, false);
Range.each (function (value, index) {
alert (value);
});
}
</script>
<input type= "button" value= "Sample Count" >

Using the Try.these () function
The Try.these () method makes it easy to implement this requirement when you want to invoke a different method until one of them is successful, and he takes a series of methods as parameters and executes them sequentially one at a time until one of them executes successfully, returning the return value of the method that was executed successfully.

In the following example, Xmlnode.text is useful in some browsers, but Xmlnode.textcontent works in other browsers. Using the Try.these () method we can get the return value of the normal working method.

<script>
function Getxmlnodevalue (xmlNode) {
Return Try.these (
function () {return xmlnode.text;},
function () {return xmlnode.textcontent;)
);
}
</script>



Ajax objects
The common method mentioned above is very good, but in the face of it, they are not the highest class of things. Are they? You probably wrote these things yourself and even have similar functions in your script. But these methods are only the tip of the iceberg.

I'm pretty sure the reason you're interested in prototype.js is probably due to its AJAX capabilities. So let's explain how this package makes it easier when you need to complete the AJAX logic.

An Ajax object is a predefined object created by this package to encapsulate and simplify the cunning code involved in writing AJAX features. This object contains a series of classes that encapsulate Ajax logic. Let's take a look at some of these classes.

Using the Ajax.request class
If you don't use any helper packages, you probably write a whole lot of code to create the XMLHttpRequest object and track its process asynchronously, then parse out the response and then process it. You'll feel very fortunate when you don't need to support more than one type of browser.

To support AJAX functionality. This package defines the Ajax.request class.

If you have an application that can communicate with the server via URL http://yoursever/app/get_sales?empID=1234&year=1998. It returns an XML response such as the following.

<?xml version= "1.0" encoding= "Utf-8"?>
<ajax-response>
<response type= "Object" id= "ProductDetails" >
<monthly-sales>
<employee-sales>
<employee-id>1234</employee-id>
<year-month>1998-01</year-month>
<sales>$8,115.36</sales>
</employee-sales>
<employee-sales>
<employee-id>1234</employee-id>
<year-month>1998-02</year-month>
<sales>$11,147.51</sales>
</employee-sales>
</monthly-sales>
</response>
</ajax-response>
It is very easy to communicate with a Ajax.request object and server and get this XML. The following example shows how it is done.

<script>
function Searchsales ()
{
var EmpID = $F (' lstemployees ');
var y = $F (' Lstyears ');
var url = ' Http://yoursever/app/get_sales ';
var pars = ' empid= ' + EmpID + ' &year= ' + y;

var myajax = new Ajax.request (
Url
{
Method: ' Get ',
Parameters:pars,
Oncomplete:showresponse
});

}
function Showresponse (originalrequest)
{
Put returned XML in the textarea
$ (' result '). Value = Originalrequest.responsetext;
}
</script>
<select id= "Lstemployees" size= "ten" >
<option value= "5" >buchanan, steven</option>
<option value= "8" >callahan, laura</option>
<option value= "1" >davolio, nancy</option>
</select>
<select id= "Lstyears" size= "3" >
<option selected= "Selected" Value= "1996" >1996</option>
<option value= "1997" >1997</option>
<option value= "1998" >1998</option>
</select>
<br><textarea Id=result cols=60 rows=10 ></textarea>
Did you notice the second object passed into the Ajax.request construction method? The parameter {method: ' Get ', Parameters:pars, Oncomplete:showresponse} represents the true wording of an anonymous object. He said that the object you passed in has a property named method value of ' get ', another property named parameters the query string containing the HTTP request, and a OnComplete property/method containing the function Showresponse.

There are other attributes that can be defined and set in this object, such as asynchronous, that can be true or false to determine whether Ajax calls to the server are asynchronous (the default value is True).

This parameter defines the options for Ajax invocation. In our example, the first parameter requests the URL through the HTTP GET command, and the query string contained in the variable pars is passed in, and the Ajax.request object invokes the Showresponse method when it completes receiving the response.

Maybe you know, XMLHttpRequest. The progress will be reported during the HTTP request. This progress is described as four different stages: Loading, Loaded, Interactive, or Complete. You can make the Ajax.request object invoke the custom method at any stage, Complete is the most commonly used one. You want to invoke a custom method simply by providing a custom method object in the requested option parameter named Onxxxxx property/method. Just like the oncomplete in our example. The method you pass in will be invoked with one parameter, which is the XMLHttpRequest object itself. You will use this object to get the returned data and perhaps check the Status property that contains the HTTP result code in this call.

There are two other useful options to handle the results. We can pass in a method at the onsuccess option, which is invoked when the Ajax is executed correctly, or, conversely, by passing a method at the OnFailure option, which is invoked when an error occurs on the server side. As the ONXXXXX option passes in, the two are called into a XMLHttpRequest object with an AJAX request.

Our example does not deal with this XML response in any interesting way, we just put this XML into a text field. A typical application of this response is likely to be finding the desired information, and then updating some elements of the page, or perhaps even making some XSLT transformations that produce some HTML on the page.

In version 1.4.0, a new event-return external rationale was introduced. If you have a piece of code that always executes for a particular event, regardless of which Ajax call throws it, you can use the new Ajax.responders object.

Let's say you want to show some hint effects, like a rotating icon, when an Ajax call is running, you can use two global event handler, one to display the icon at the start of the first call, and the other to hide the icon when the last call completes. Look at the example below.

<script>
var myglobalhandlers = {
Oncreate:function () {
Element.show (' systemworking ');
},
Oncomplete:function () {
if (Ajax.activerequestcount = = 0) {
Element.hide (' systemworking ');
}
}
};
Ajax.Responders.register (myglobalhandlers);
</script>
<div id= ' systemworking ' >Loading...</div>
For a more complete explanation, refer to the Ajax.request Reference and Ajax options.

[1] [2] [3] [4] [5] Next page



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.