Prototype Trial documents

Source: Internet
Author: User

There is no time to read prototype. Now it's okay. It has been updated to 1.5 pre1. Haha, the powerful functions have to be learned. This is another shortcut to improve your JS capabilities.

1. What is Prototype?
Maybe you haven't used it. prototype. js is a JavaScript package written by Sam Stevenson. This fantastic idea of writing a piece of code that is compatible with standards will bear the burden of creating fat clients and highly interactive WEB applications. Web 2.0 features can be easily added.

If you have recently experienced this package, you may find that the document is not one of its strengths. Like all the developers before me, I can only drag them into the source code of prototype. js and test each part of it. I think it will be nice to take notes when I study him and share it with others.

I also provided unofficial references for the objects, classes, methods, and extensions of this package.

2. Universal Methods
This package contains many predefined objects and universal methods. The obvious purpose of writing these methods is to reduce your repeated coding and usage.

Starting with Prototype1.5.x, you can operate DOM objects more conveniently as you do in the following code:

Program code
Var ele = $ ("myelement ");
Ele. hide (); // hide the DOM object compared to the previous version var ele =$ ("myelement ");
Element. hide (ele); // hide a DOM object


What are the benefits of such a change? I think it is more object-oriented, and the second is to facilitate code prompts In the IDE in the future.

2.1. 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. The following example will describe this to you.

Program code
<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 of this method is that you can pass in the id string or element object, which makes it very useful when creating a method that can pass in any form of parameters.

2.2. Use the $ F () method
The $ F () method is another popular shorthand. It returns the value of any input form control, such as a text box or a drop-down box. This method can pass in the element id or element itself.

Program code
<Script>
Function test3 ()
{
Alert ($ F ('username '));
}
</Script>

<Input type = "text" id = "userName" value = "Joe Doe"> <br>
<Input type = "button" value = Test3 onclick = "test3 ();"> <br>


2.3. Use Try. these () method
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.

Program code
<Script>
Function getXmlNodeValue (xmlNode ){
Return Try. these (
Function () {return xmlNode. text ;},
Function () {return xmlNode. textContent ;)
);
}
</Script>


3. 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 some of them.

3.1. Use the Ajax. Request class
If you do not use any help packages, you may write a large amount of code to create an XMLHttpRequest object and asynchronously track its process, 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.

Program code
<? 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.

Program code
<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 = "10" onchange = "searchSales ()">
<Option value = "5"> Buchanan, Steven </option>
<Option value = "8"> Callahan, Laura </option>
<Option value = "1"> Davolio, Nancy </option>
</Select>
<Select id = "lstYears" size = "3" onchange = "searchSales ()">
<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>


Do you see 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.

3.2. 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.

Program code
<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.

Program code
<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 rather than simply HTML markup, 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.

Prototype Learning materials include:
Prototype14 reference
Prototype 1.3 source code unread .txt
Prototype 1.5 reference diagram
Prototype 1.5pre1.js
Prototype 1.4.js
Click here to download

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.