Prototype. js usage manual (excerpt)

Source: Internet
Author: User
Tags javascript extension
Prototype. js 1.4 developer manual 1 (reproduced)

Prototype. JS is a very elegant JavaScript base class library, which has made a lot of extensions to Javascript, and supports Ajax very well. There are multiple effect libraries based on this library in foreign countries and they have done a great job.
Prototype. JS is not only a JS library with great practical value, but also has a high learning value, therefore, I strongly recommend B/S developers and those interested in JS development to browse some of itsSource codeThere are a lot of Pearl, you will definitely think that reading its sourceCodeIt is a kind of enjoyment. Of course you must understand it.
Someone has written the source code explanation for version 1.3 on the Internet. You can check it out. However, version 1.4 has been greatly expanded, so I hope some friends can write the source code of version 1.4.
Notes:

What is prototype. js?

In case you haven't used the famous prototype. JS, let me tell you that prototype. JS is a javascript class library written by Sam Stephen enson. This fantastic idea and compatible with standard class libraries can help you easily build rich client pages with highly interactive web features.

If you try to use it recently, you probably know that the document is not the author's strength. Like many developers who used this class library before, at the beginning, I had to read prototype. js source code and experiment with its functions. I think it is good to share what I learned with you after I finish learning it.

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

When reading this document, developers familiar with Ruby will notice that some of Ruby's built-in classes are very similar to the extension implementation of this class library.
RelatedArticle

Advanced JavaScript guide.
Some practical functions

This class library has many predefined objects and practical functions. These classes are clearly designed to free you from repeated typing.
Use the $ () method

$ () Is a document that is used too frequently in the Dom. A convenient shorthand for the getelementbyid () method. Like this Dom method, this method returns the element of the ID passed in by the parameter.

This is better than the DOM method. You can input multiple IDS as parameters and then $ () returns 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 ', 'mytherdiv ');
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 onclick = "test1 ();"> <br>
<Input type = "button" value = Test2 onclick = "Test2 ();"> <br>
</Body>
</Html>

Another benefit is that this function can pass in the ID of the object represented by string or the object itself, which is very useful when creating other functions that can pass two types of parameters.
Use the $ F () function

The $ F () function is another popular "shortcut key", which can be used to return the value of any form input control, such as text box and drop-down list. This method can also use the element ID or element itself as the parameter.

<SCRIPT>
Function test3 ()
{
Alert ($ F ('username '));
}
</SCRIPT>
<Input type = "text" id = "username" value = "joe doe"> <br>
<Input type = "button" value = test3 onclick = "test3 ();"> <br>

Use the $ A () function

The $ A () function converts a single parameter it receives into an array object.

This method, combined with the array class extended by this class library, can easily convert any enumerated list into or copy to an array object. A recommended method is to convert Dom node lists into a common array object for more efficient traversal. See the following example.

<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 = "10">
<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" onclick = "showoptions ();">

Use the $ H () function

The $ H () function converts some objects into an enumerated hash object similar to the Union 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 ();
Alert (H. toquerystring (); // displays: First = 10 & Second = 20 & third = 30
}
</SCRIPT>

Use the $ R () function

$ R () is the abbreviation of New objectrange (lowbound, upperbound, excludebounds.

Jump to the objectrange class document to see a complete description of this class. At this time, let's take a look at an example to show which methods can be replaced by this abbreviation. Other related knowledge can be found in the enumerable object document.

<SCRIPT>
Function demodollar_r (){
VaR range = $ R (10, 20, false );
Range. Each (function (value, index ){
Alert (value );
});
}
</SCRIPT>
<Input type = "button" value = "sample count" onclick = "demodollar_r ();">

Use the try. These () function

Try. the these () method makes it easy to implement this requirement when you want to call different methods until one of them is successful and normal, he uses a series of methods as parameters and executes these methods one by one in sequence until one of them is successfully executed, and returns the return value of the method that is successfully executed.

In the following example, xmlnode. Text is useful in Some browsers, but xmlnode. textcontent works normally in other browsers. Using the try. These () method, we can get the return value of the method that works normally.

<SCRIPT>
Function getxmlnodevalue (xmlnode ){
Return try. These (
Function () {return xmlnode. Text ;},
Function () {return xmlnode. textcontent ;)
);
}
</SCRIPT>

Ajax object

The common methods mentioned above are very good, but in the face of them, they are not the highest level. Are they? You may have compiled these methods by yourself or even have similar functions in your script. But these methods are just the tip of the iceberg.

I'm sure the reason you are interested in prototype. JS is probably because of its Ajax capabilities. So Let's explain how to make this package easier when you need to complete Ajax logic.

An Ajax object is a predefined object created by this package. To encapsulate and simplify the tricky Code involved in writing Ajax functions. This object contains a series of classes that encapsulate Ajax logic. Let's take a look at several of these classes.
Use the Ajax. Request class

If you do not use any helpProgramPackage. You may write a large amount of code to create an XMLHTTPRequest object and asynchronously track its process. Then parse the response and process it. You are very lucky when you do not need to support more than one type of browser.

To support Ajax functions. This package defines the Ajax. Request class.

Suppose you have an application that can use URL http: // yoursever/APP/get_sales? Empid = 1234 & year = 1998 communicates with the server. It returns the following XML response.

<? 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 use the Ajax. Request object to communicate with the server and obtain the XML file. The following example demonstrates how it is completed.

<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 });

}< br> function showresponse (originalrequest)
{< br> // put returned XML in the textarea
$ ('result '). value = originalrequest. responsetext;
}< br>
Buchanan, Steven Callahan, laura davolio, nancy
1996 1997 1998

Have you noticed the second object passed in the Ajax. Request constructor? The {method: 'get', parameters: pars, oncomplete: showresponse} parameter represents the actual method of writing an anonymous object. It indicates that the object you pass in has an attribute named 'get' with the method value, and another attribute named parameters contains the query string of the HTTP request, and an oncomplete attribute/method contains the showresponse function.

Some other attributes can be defined and set in this object. For example, asynchronous can be true or false to determine whether Ajax calls to the server are asynchronous (the default value is true ).

This parameter defines the Ajax call options. In our example, the first parameter uses the http get command to request the URL and passes in the query string contained in the variable pars, Ajax. when the request object receives a response, it will call the showresponse method.

You may know that XMLHttpRequest will report progress during the HTTP request. This progress is described as four different stages: Loading, loaded, interactive, or complete. You can use Ajax. Request objects to call custom methods at any stage. Complete is the most commonly used one. To call a custom method, you only need to provide a custom method object in the onxxxxx attribute/method in the request's option parameter. Like oncomplete in our example. The method you pass in will be called with a parameter, which is the XMLHTTPRequest object itself. You will use this object to get the returned data and may check the status attribute that contains the HTTP result code in this call.

There are two other useful options for processing results. We can pass in a method in the onsuccess option. After Ajax is executed correctly, we can call the method in the onfailure option. If an error occurs on the server side, we can call the method. Like the method passed in by the onxxxxx option, both of them also pass in an XMLHTTPRequest object with an Ajax request when called.

Our example does not use any interesting method to process this XML response. We just put this XML into a text field. A typical application of this response is probably to find the desired information, then update some elements on the page, or even perform some XSLT transformations to generate some HTML on the page.

In version 1.4.0, a new Event Callback principle is introduced. If you have a piece of code that is always executed for a special event, and no matter which Ajax call causes it, you can use the new Ajax. Responders object.

Suppose you want to display some prompts when an Ajax call is running, such as a continuously rotating icon, you can use two global event handler to do so, one shows the icon at the beginning of the first call, and the other hides the icon at the end of the last call. Let's 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 more information, see Ajax. Request and Ajax options.

Use the Ajax. Updater class

If the information returned by the other end of your server is already HTML, using the Ajax. Updater class in this package will make your life easier. You only need to provide the element that needs to be filled with the HTML returned by the Ajax request. The example is clearer than what I wrote.

<SCRIPT>
Function gethtml ()
{
VaR url = 'HTTP: // yourserver/APP/getsomehtml ';
VaR pars = 'someparameter = abc ';
VaR myajax = new Ajax. Updater ('placeholder ', URL, {method: 'get', parameters: pars });

}
</SCRIPT>
<Input type = button value = gethtml onclick = "gethtml ()">
<Div id = "Placeholder"> </div>

As you can see, this code is more concise than the previous example, excluding the oncomplete method, but an element ID is introduced in the constructor. Let's slightly modify the code to describe how to handle server segment errors on the client.

We will add more options to specify a method to handle errors. This is done with the onfailure option. We also specify a placeholder that will be filled only after successful requests. To accomplish this, we modified the first parameter from a simple element ID to an object with two attributes, success (used when everything is OK) and failure (used when something goes wrong). In the following example, the failure attribute is not used, but the reporterror method is used only in onfailure.

<SCRIPT>
Function gethtml ()
{
VaR url = 'HTTP: // yourserver/APP/getsomehtml ';
VaR pars = 'someparameter = abc ';

VaR myajax = new Ajax. Updater ({success: 'holder'}, URL, {method: 'get', parameters: pars, onfailure: reporterror });

}
Function reporterror (request)
{
Alert ('sorry. There was an error .');
}
</SCRIPT>
<Input type = button value = gethtml onclick = "gethtml ()">
<Div id = "Placeholder"> </div>

If your server logic is to return JavaScript code together with the HTML Tag, the Ajax. Updater object can execute that JavaScript code. To make this object treat the response as JavaScript, you just need to simply add the evalscripts: True attribute to the object constructor method of the final parameter. However, it is worth noting that, as the option name evalscripts implies, these scripts will be executed, but they will not be added to the page script. "What is the difference ?", You may ask this question. We assume that the request address returns something like this:

<Script language = "JavaScript" type = "text/JavaScript">
Function sayhi (){
Alert ('Hi ');
}
</SCRIPT>
<Input type = button value = "Click me" onclick = "sayhi ()">

If you have tried this before, you know that these scripts won't work as expected because they will be executed, but a script like above does not create a function named sayhi, and it does not do anything. To create a function, we should change the code to the following:

<Script language = "JavaScript" type = "text/JavaScript">
Sayhi = function () {alert ('Hi ');};

</SCRIPT>
<Input type = button value = "Click me" onclick = "sayhi ()">

Why do we not use the VaR keyword to declare this variable in the above Code (sayhi ), because the created function is only a local variable of the current script block (at least in IE ). Without the VaR keyword, the scope of the created object is the expected window.

For more information, see Ajax. Updater reference and options reference.
Enumeration... Oh! Oh!

You know, we all do this for loop. Create an array, use elements to organize them, and then create a loop structure (such as for, foreach, while) to access each element through the index number, use this element to perform some operations.

When you think of this, you will find that you will use an array sooner or later almost every time you write loop code. If the array object can provide more functions for their iterators, isn't it nice? Indeed, there are actually a lotProgramming LanguageThese functions are provided in their array or other similar structures (such as collections and lists.

Now, prototype. js gives us an enumerable object, which provides many tips for interacting with iterative data. Compared with the original JS object, prototype. JS is upgraded to another level. It extends all functions used for enumeration for array class S.
Loop, ruby-style

In standard JavaScript, if you want to display all elements in an array, you can write well like the following code:

<SCRIPT>
Function showlist (){
VaR Simpsons = ['Homer', 'marge', 'lisa ', 'bart', 'meg'];
For (I = 0; I <Simpsons. length; I ++) {alert (Simpsons [I]);}

}
</SCRIPT>
<Input type = "button" value = "show list" onclick = "showlist ();">

With our new best friend prototype. JS, we can write it like this.

Function showlist (){
VaR Simpsons = ['Homer', 'marge', 'lisa ', 'bart', 'meg'];
Simpsons. Each (function (familymember) {alert (familymember );});

}

You may think, "a very strange way... is relatively old. This syntax is too weird ". Oh, in the above example, there is indeed nothing. In this simple and dying example, it has not changed much. However, please continue reading it.

Before proceeding to the following content, do you notice the function that is passed to the each function as a parameter? We understand it as an iterator function.
Your Arrays on steroids

As we mentioned above, using the same attributes and functions as elements in your array as the same type is very common (I don't know whether to translate them into common or vulgar. Let's take a look at how to use our new powerful arrays iteration function.

Locate an element according to the standard.

<SCRIPT>
Function findemployeebyid (emp_id ){
VaR ListBox = $ ('lstemployees ')
VaR Options = ListBox. getelementsbytagname ('option ');
Options = $ A (options );
VaR opt = options. Find (function (employee ){
Return (employee. value = emp_id );
});
Alert (OPT. innerhtml); // displays the employee name
}
</SCRIPT>
<Select id = "lstemployees" size = "10">
<Option value = "5"> Buchanan, Steven </option>
<Option value = "8"> Callahan, Laura </option>
<Option value = "1"> davolio, Nancy </option>
</SELECT>
<Input type = "button" value = "find Laura" onclick = "findemployeebyid (8);">

Now let's take a look at how to filter elements in an array and get the desired members from each element.



This text has
A lot of
Links . some are
external
and some are Local


The code above is just a small practice that makes people fall in love with this syntax. See all functions of enumerable and array.

Prototype. js reference

Javascript Extension

One way to implement powerful functions of the prototype. js class library is to expand the existing JavaScript class.

Object Extension

Method kind arguments description
Extend (destination, source) Static destination: any object, source: Any object provides a method to inherit objects by copying all source object attributes and functions to the target function.
Inspect (targetobj) Static targetobj: Any object returns readable text descriptions about the target object. If the object instance does not define an inspect function, the value of the tostring function is returned by default.

Number Extension

Method kind arguments description
Tocolorpart () instance (none) returns the hexadecimal representation of the number. It is useful when converting an RGB number into an HTML representation.
Succ () instance (none) returns the next number, which can be used in iterative call scenarios.
Times (iterator) instance iterator: A function object conforming to function (INDEX) callthe iterator function repeatedly passing the current index in the index argument. call the iterator function repeatedly and pass the index parameter of the current index to the iterator.

The following example shows 0-9 in a prompt box.

<SCRIPT>
Function demotimes (){
VaR n = 10;
N. Times (function (INDEX ){
Alert (INDEX );
});
/***************************
* You coshould have also used:
* (10). Times (....);
***************************/
}
</SCRIPT>
<Input type = button value = "test number. Times ()" onclick = "demotimes ()">

Function Extension

Method kind arguments description
BIND (object) instance object: The object that owns the method returns the function instance. This instance has the same structure as the source function, but it has been bound to the object provided by the parameter, that is to say, the this pointer in function points to the parameter object.
Bindaseventlistener (object) instance object: The object that owns the method usage is the same as the above bind, the difference is used to bind events.

Let's see how to use these extensions.

<Input type = checkbox id = mychk value = 1> test?
<SCRIPT>
// Declaring the class
VaR checkboxwatcher = Class. Create ();
// Defining the rest of the class implementation
Checkboxwatcher. Prototype = {
Initialize: function (chkbox, message ){
This. chkbox = $ (chkbox );
This. Message = message;
// Assigning our method to the event
This. chkbox. onclick = This. showmessage. bindaseventlistener (this );

},
Showmessage: function (EVT ){
Alert (this. Message + '(' + EVT. Type + ')');
}
};
VaR watcher = new checkboxwatcher ('mychk', 'changed ');
</SCRIPT>

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.