I haven't had time to watch prototype. Now it's fine, it has been updated to 1.5 pre1. Haha, I have to learn powerful functions. This is another shortcut to improving my JS capabilities.
1. What is Prototype?
Maybe you haven't used it yet, it's a JavaScript package written by Sam Stephenson. This idea of writing a well-compliant piece of code that is compatible with standards will bear the burden of creating fat clients, highly interactive WEB applications. Easily add Web 2.0 features.
If you have recently experienced this package, you will most likely find that documentation is not one of its strengths. Like all developers before me, I could only dive into the source code head-on and experiment with every part of it. I think it would be great to take notes and share them with others when I was studying him.
I also provide unofficial references to objects, classes, methods and extensions for this package.
2. General method
This package contains many predefined objects and universal methods. The obvious purpose of writing these methods is to reduce your massive repetitive encodings and idioms.
Starting from the Prototype 1. version, you can more conveniently operate the DOM object as shown in the following code:
Program code
var ele = $("myelement");
(); //Hide DOM object comparison in the previous version var ele = $("myelement");
(ele); //Hide DOM object
What are the benefits of such a change? I think it is more object-oriented, and secondly, it is to facilitate future code prompts in IDEs.
2.1. Use the $() method
The $() method is a convenient abbreviation for using too frequently in the DOM method. Just like this DOM method, this method returns the element of the id passed in the parameter.
This is better than the method in DOM. You can pass in multiple ids as parameters and then $() returns an Array object with all the required elements. The following examples will describe these to you.
Program code
<HTML>
<HEAD>
<TITLE> Test Page </TITLE>
<script src="prototype-1.3."></script>
<script>
function test1()
{
var d = $('myDiv');
alert();
}
function test2()
{
var divs = $('myDiv','myOtherDiv');
for(i=0; i<; i++)
{
alert();
}
}
</script>
</HEAD>
<BODY>
<div >
<p>This is a paragraph</p>
</div>
<div >
<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 the element object itself, which makes it very useful when creating methods that can pass in any form of parameters.
2.2. Use the $F() method
The $F() method is another very popular abbreviation. It can return the value of any input form control, such as a text box or a drop-down box. This method can pass in the element's id or the element itself.
Program code
<script>
function test3()
{
alert( $F('userName') );
}
</script>
<input type="text" value="Joe Doe"><br>
<input type="button" value=Test3 onclick="test3();"><br>
2.3. Use the () method
() method makes it very easy to implement the requirement that when you want to call different methods until one of them succeeds, it takes a series of methods as parameters and executes these methods one by one in order until one of them is successfully executed, returning the return value of the method that was successfully executed.
In the following example, it is good in some browsers, but it works properly in others. Using the() method we can get the return value of the method that works normally.
Program code
<script>
function getXmlNodeValue(xmlNode){
return (
function() {return ;},
function() {return ;)
);
}
</script>
3. Ajax object
The common methods mentioned above are very good, but when it comes to it, they are not the most advanced things. Are they? You may have written these yourself and even have similar functions in your scripts. But these methods are just the tip of the iceberg.
I'm pretty sure the reason you're interested in is most likely due to its AJAX capabilities. So let's explain how this package makes it easier when you need to complete AJAX logic.
The Ajax object is a predefined object created by this package to encapsulate and simplify the crafty 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 Class
If you don't use any help packages, you're likely writing a whole lot of code to create an XMLHttpRequest object and track its process asynchronously, then parse out the response and then process it. You will feel very lucky when you don't need to support more than one type of browser.
In order to support the AJAX function. This package defines the 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 the following XML response.
Program code
<?xml version="1.0" encoding="utf-8" ?>
<ajax-response>
<response type="object" >
<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 simple to communicate with the server and get this XML using an object. The following example demonstrates how it is done.
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 (
url,
{method: 'get', parameters: pars, onComplete: showResponse}
);
}
function showResponse(originalRequest)
{
//put returned XML in the textarea
$('result').value = ;
}
</script>
<select size="10" onchange="searchSales()">
<option value="5">Buchanan, Steven</option>
<option value="8">Callahan, Laura</option>
<option value="1">Davolio, Nancy</option>
</select>
<select 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>
Have you seen the second object passed in the construction method? Parameters {method: 'get', parameters: pars, onComplete: showResponse} Denotes the true writing of an anonymous object. It indicates that the object you pass in has a property named method with a value of 'get', another property named parameters containing the query string for HTTP requests, and an onComplete property/method containing the function showResponse.
There are some other properties that can be defined and set in this object, such as asynchronous, which can be true or false to determine whether AJAX's call to the server is asynchronous (the default value is true).
This parameter defines the options for AJAX calls. In our example, when the first parameter requests that url through the HTTP GET command, the query string contained in the variable pars is passed in. The object will call the showResponse method when it completes receiving the response.
Maybe you know that XMLHttpRequest will report progress during HTTP requests. This progress is described as four different stages: Loading, Loaded, Interactive, or Complete. You can make the object call custom methods at any stage, and Complete is the most commonly used one. To call a custom method, you only need to simply provide a custom method object in the attribute named onXXXXX property/method in the requested option parameter. Just 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 perhaps check the status attribute containing the HTTP result code in this call.
There are two other useful options for processing results. We can pass a method in the onSuccess option, and call it when AJAX is executed correctly. On the contrary, we can also pass a method in the onFailure option, and call it when an error occurs on the server side. Just like the method passed in the onXXXXX option, these two also pass in an XMLHttpRequest object with an AJAX request when called.
Our example does not handle this XML response in any interesting way, we just put this XML into a text field. A typical application to this response is likely to find the information you want, and then update certain elements in the page, or even do some XSLT conversions to generate some HTML in the page.
3.2. Use Class
If the information returned by the other end of your server is already HTML, then using the classes in this package will make your life easier. To use it, you just need to provide which element needs to be filled with 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 ('placeholder', url, {method: 'get', parameters: pars});
}
</script>
<input type=button value=GetHtml onclick="getHTML()">
<div ></div>
As you can see, this code is more concise than the previous example, not including the onComplete method, but an element id is passed into the constructor. Let's modify the code a little to describe how it becomes possible to handle server segmentation errors on the client.
We will add more options to specify a way to handle errors. This is done with the onFailure option.
We also specified a placeholder that will be populated only after a successful request. 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 only the reportError method is used at onFailure.
Program code
<script>
function getHTML()
{
var url = 'http://yourserver/app/getSomeHTML';
var pars = 'someParameter=ABC';
var myAjax = new (
{success: 'placeholder'},
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 ></div>
If your server logic returns JavaScript code instead of a simple HTML tag, the object can execute that JavaScript code. In order to make this object treat the response to JavaScript, you only need to simply add the evalScripts: true attribute to the object constructor of the last parameter.
Recently, I started to do otalk, which was based on prototype1.4. Later, because I added scriptaculous 1.6.1, she asked the version of prototype to be 1.5, so she upgraded to 1.5. I learned how to use scriptaculous when I watched demo.
The usage is sorted out later, because the effect is not satisfied many times during use, and I want to read the code but can’t understand it. After a torture, I made up my mind to understand the code of scriptaculous and prototype!
Here is my study notes, there may be no logic in any order. When I finish my study, I will sort it out.
First of all, the definition class. Looking at some introductions from Teacher Xiaoxiao, I saw it myself and tried it. Often, I realized many things after reading them, but in fact they were still much different.
var Class = {
create: function() {
return function() {
(this, arguments);
}
}
}
Define a class function as a template or prototype for creating the class.
How to use
var llinzzi= ();
= {
initialize:function(){
('Instance was created');
},
fun1:function(){('The method is called by the instance');}
}
var linChild = new llinzzi();
Run, output 'instance is created' indicating that initialize is called when creating the instance.
Review in Class code
return function() {
(this, arguments);
}
It can be seen that when the create method is executed, the call starts.
linChild.fun1();
Output 'The method is called by the instance', fun1 method is called successfully
That is, when the prototype(); method is used to create an object, initialize is executed as a special method when creating an instance and is used to initialize.
Continuing
= function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
Usage
(Target, Source);
What makes me strange is a piece of code in scriptaculous
var options = ({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || {});
Since it is to define an option, why do you still need to use methods?
direct
var options ={
greedy: true,
hoverclass: null,
tree: false
}
Isn't it enough? Wait, there are problems. There are arguments[1]||{} later. This should be the target. The target is the parameter of the function. After analysis, get the parameters. If there is no parameter, it is {}, which is {}. If there is, it is also in the format of {hoverclass:'xx'}. Oh, it turns out that defining options is not that simple. First, see if there are parameters. Whether there are or not, use the method to append or overwrite the object in the parameter to the previous { gr eedy: true, hoverclass: null, �
I have to admire it, and define it one by one sentence, and the default value is set.
The more you watch, the more interesting it becomes, keep watching
1. What is Prototype?
Maybe you haven't used it yet, it's a JavaScript package written by Sam Stephenson. This idea of writing a well-compliant piece of code that is compatible with standards will bear the burden of creating fat clients, highly interactive WEB applications. Easily add Web 2.0 features.
If you have recently experienced this package, you will most likely find that documentation is not one of its strengths. Like all developers before me, I could only dive into the source code head-on and experiment with every part of it. I think it would be great to take notes and share them with others when I was studying him.
I also provide unofficial references to objects, classes, methods and extensions for this package.
2. General method
This package contains many predefined objects and universal methods. The obvious purpose of writing these methods is to reduce your massive repetitive encodings and idioms.
Starting from the Prototype 1. version, you can more conveniently operate the DOM object as shown in the following code:
Program code
var ele = $("myelement");
(); //Hide DOM object comparison in the previous version var ele = $("myelement");
(ele); //Hide DOM object
What are the benefits of such a change? I think it is more object-oriented, and secondly, it is to facilitate future code prompts in IDEs.
2.1. Use the $() method
The $() method is a convenient abbreviation for using too frequently in the DOM method. Just like this DOM method, this method returns the element of the id passed in the parameter.
This is better than the method in DOM. You can pass in multiple ids as parameters and then $() returns an Array object with all the required elements. The following examples will describe these to you.
Program code
<HTML>
<HEAD>
<TITLE> Test Page </TITLE>
<script src="prototype-1.3."></script>
<script>
function test1()
{
var d = $('myDiv');
alert();
}
function test2()
{
var divs = $('myDiv','myOtherDiv');
for(i=0; i<; i++)
{
alert();
}
}
</script>
</HEAD>
<BODY>
<div >
<p>This is a paragraph</p>
</div>
<div >
<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 the element object itself, which makes it very useful when creating methods that can pass in any form of parameters.
2.2. Use the $F() method
The $F() method is another very popular abbreviation. It can return the value of any input form control, such as a text box or a drop-down box. This method can pass in the element's id or the element itself.
Program code
<script>
function test3()
{
alert( $F('userName') );
}
</script>
<input type="text" value="Joe Doe"><br>
<input type="button" value=Test3 onclick="test3();"><br>
2.3. Use the () method
() method makes it very easy to implement the requirement that when you want to call different methods until one of them succeeds, it takes a series of methods as parameters and executes these methods one by one in order until one of them is successfully executed, returning the return value of the method that was successfully executed.
In the following example, it is good in some browsers, but it works properly in others. Using the() method we can get the return value of the method that works normally.
Program code
<script>
function getXmlNodeValue(xmlNode){
return (
function() {return ;},
function() {return ;)
);
}
</script>
3. Ajax object
The common methods mentioned above are very good, but when it comes to it, they are not the most advanced things. Are they? You may have written these yourself and even have similar functions in your scripts. But these methods are just the tip of the iceberg.
I'm pretty sure the reason you're interested in is most likely due to its AJAX capabilities. So let's explain how this package makes it easier when you need to complete AJAX logic.
The Ajax object is a predefined object created by this package to encapsulate and simplify the crafty 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 Class
If you don't use any help packages, you're likely writing a whole lot of code to create an XMLHttpRequest object and track its process asynchronously, then parse out the response and then process it. You will feel very lucky when you don't need to support more than one type of browser.
In order to support the AJAX function. This package defines the 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 the following XML response.
Program code
<?xml version="1.0" encoding="utf-8" ?>
<ajax-response>
<response type="object" >
<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 simple to communicate with the server and get this XML using an object. The following example demonstrates how it is done.
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 (
url,
{method: 'get', parameters: pars, onComplete: showResponse}
);
}
function showResponse(originalRequest)
{
//put returned XML in the textarea
$('result').value = ;
}
</script>
<select size="10" onchange="searchSales()">
<option value="5">Buchanan, Steven</option>
<option value="8">Callahan, Laura</option>
<option value="1">Davolio, Nancy</option>
</select>
<select 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>
Have you seen the second object passed in the construction method? Parameters {method: 'get', parameters: pars, onComplete: showResponse} Denotes the true writing of an anonymous object. It indicates that the object you pass in has a property named method with a value of 'get', another property named parameters containing the query string for HTTP requests, and an onComplete property/method containing the function showResponse.
There are some other properties that can be defined and set in this object, such as asynchronous, which can be true or false to determine whether AJAX's call to the server is asynchronous (the default value is true).
This parameter defines the options for AJAX calls. In our example, when the first parameter requests that url through the HTTP GET command, the query string contained in the variable pars is passed in. The object will call the showResponse method when it completes receiving the response.
Maybe you know that XMLHttpRequest will report progress during HTTP requests. This progress is described as four different stages: Loading, Loaded, Interactive, or Complete. You can make the object call custom methods at any stage, and Complete is the most commonly used one. To call a custom method, you only need to simply provide a custom method object in the attribute named onXXXXX property/method in the requested option parameter. Just 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 perhaps check the status attribute containing the HTTP result code in this call.
There are two other useful options for processing results. We can pass a method in the onSuccess option, and call it when AJAX is executed correctly. On the contrary, we can also pass a method in the onFailure option, and call it when an error occurs on the server side. Just like the method passed in the onXXXXX option, these two also pass in an XMLHttpRequest object with an AJAX request when called.
Our example does not handle this XML response in any interesting way, we just put this XML into a text field. A typical application to this response is likely to find the information you want, and then update certain elements in the page, or even do some XSLT conversions to generate some HTML in the page.
3.2. Use Class
If the information returned by the other end of your server is already HTML, then using the classes in this package will make your life easier. To use it, you just need to provide which element needs to be filled with 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 ('placeholder', url, {method: 'get', parameters: pars});
}
</script>
<input type=button value=GetHtml onclick="getHTML()">
<div ></div>
As you can see, this code is more concise than the previous example, not including the onComplete method, but an element id is passed into the constructor. Let's modify the code a little to describe how it becomes possible to handle server segmentation errors on the client.
We will add more options to specify a way to handle errors. This is done with the onFailure option.
We also specified a placeholder that will be populated only after a successful request. 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 only the reportError method is used at onFailure.
Program code
<script>
function getHTML()
{
var url = 'http://yourserver/app/getSomeHTML';
var pars = 'someParameter=ABC';
var myAjax = new (
{success: 'placeholder'},
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 ></div>
If your server logic returns JavaScript code instead of a simple HTML tag, the object can execute that JavaScript code. In order to make this object treat the response to JavaScript, you only need to simply add the evalScripts: true attribute to the object constructor of the last parameter.
Recently, I started to do otalk, which was based on prototype1.4. Later, because I added scriptaculous 1.6.1, she asked the version of prototype to be 1.5, so she upgraded to 1.5. I learned how to use scriptaculous when I watched demo.
The usage is sorted out later, because the effect is not satisfied many times during use, and I want to read the code but can’t understand it. After a torture, I made up my mind to understand the code of scriptaculous and prototype!
Here is my study notes, there may be no logic in any order. When I finish my study, I will sort it out.
First of all, the definition class. Looking at some introductions from Teacher Xiaoxiao, I saw it myself and tried it. Often, I realized many things after reading them, but in fact they were still much different.
var Class = {
create: function() {
return function() {
(this, arguments);
}
}
}
Define a class function as a template or prototype for creating the class.
How to use
var llinzzi= ();
= {
initialize:function(){
('Instance was created');
},
fun1:function(){('The method is called by the instance');}
}
var linChild = new llinzzi();
Run, output 'instance is created' indicating that initialize is called when creating the instance.
Review in Class code
return function() {
(this, arguments);
}
It can be seen that when the create method is executed, the call starts.
linChild.fun1();
Output 'The method is called by the instance', fun1 method is called successfully
That is, when the prototype(); method is used to create an object, initialize is executed as a special method when creating an instance and is used to initialize.
Continuing
= function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
Usage
(Target, Source);
What makes me strange is a piece of code in scriptaculous
var options = ({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || {});
Since it is to define an option, why do you still need to use methods?
direct
var options ={
greedy: true,
hoverclass: null,
tree: false
}
Isn't it enough? Wait, there are problems. There are arguments[1]||{} later. This should be the target. The target is the parameter of the function. After analysis, get the parameters. If there is no parameter, it is {}, which is {}. If there is, it is also in the format of {hoverclass:'xx'}. Oh, it turns out that defining options is not that simple. First, see if there are parameters. Whether there are or not, use the method to append or overwrite the object in the parameter to the previous { gr eedy: true, hoverclass: null, �
I have to admire it, and define it one by one sentence, and the default value is set.
The more you watch, the more interesting it becomes, keep watching