【引用】http://www.cnblogs.com/thinhunan/archive/2006/04/01/DeveloperNotesForPrototype.html

 


prototype.js是一個(gè)非常優(yōu)雅的javascript基礎(chǔ)類庫,對(duì)javascript做了大量的擴(kuò)展,而且很好的支持Ajax,國(guó)外有多個(gè)基于此類庫實(shí)現(xiàn)的效果庫,也做得很棒。
prototype.js不僅是一個(gè)有很大實(shí)用價(jià)值的js庫,而且有很高的學(xué)習(xí)價(jià)值,所以我強(qiáng)烈建議B/S開發(fā)人員和對(duì)JS開發(fā)感興趣的朋友去瀏覽一些它的源代碼,
其中有很多的珠璣,你絕對(duì)會(huì)覺得讀它的源代碼是一種享受,當(dāng)然要讀得懂,呵呵。
網(wǎng)上也有人寫過1.3版的源碼解讀,大家可以找來看看。不過1.4版做了很大的擴(kuò)充,所以希望有朋友寫出1.4版的源碼解讀。

prototype.js是什么?

萬一你沒有使用過大名鼎鼎的prototype.js,那么讓我來告訴你,prototype.js是由Sam Stephenson寫的一個(gè)javascript類庫。這個(gè)構(gòu)思奇妙,而且兼容標(biāo)準(zhǔn)的類庫,能幫助你輕松建立有高度互動(dòng)的web2.0特性的富客戶端頁面。

如果你最近嘗試使用它,你大概了解到文檔并不是作者的一個(gè)強(qiáng)項(xiàng)。和在我以前使用這個(gè)類庫的不少開發(fā)者一樣,一開始,我不得不一頭扎進(jìn)閱讀prototype.js的源代碼和實(shí)驗(yàn)它的功能中。我想,在我學(xué)習(xí)完它之后,把我學(xué)到的東西分享給大家是件不錯(cuò)的事。

同時(shí),在本文中,我也將提供一個(gè)關(guān)于這個(gè)類庫提供的objects,classes,functions,extensions這對(duì)東東的非官方參考

在閱讀這個(gè)文檔時(shí),熟悉Ruby的開發(fā)者將會(huì)注意到Ruby的一些內(nèi)建類和本類庫擴(kuò)展實(shí)現(xiàn)之間非常相似。

相關(guān)文章

Advanced JavaScript guide.

一些實(shí)用的函數(shù)

這個(gè)類庫帶有很多預(yù)定義的對(duì)象和實(shí)用函數(shù),這些東東的目的顯然是把你從一些重復(fù)的打字中解放出來 。

使用$()方法

$() 方法是在DOM中使用過于頻繁的 document.getElementById() 方法的一個(gè)便利的簡(jiǎn)寫,就像這個(gè)DOM方法一樣,這個(gè)方法返回參數(shù)傳入的id的那個(gè)元素。

比起DOM中的方法,這個(gè)更勝一籌。你可以傳入多個(gè)id作為參數(shù)然后 $() 返回一個(gè)帶有所有要求的元素的一個(gè) Array 對(duì)象。

<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 onclick="test1();"><br>
<input type="button" value=Test2 onclick="test2();"><br>
</BODY>
</HTML>

另外一個(gè)好處是,這個(gè)函數(shù)能傳入用string表示的對(duì)象ID,也可以傳入對(duì)象本身,這樣,在建立其它能傳兩種類型的參數(shù)的函數(shù)時(shí)非常有用。

使用$F()函數(shù)

$F()函數(shù)是另一個(gè)大收歡迎的“快捷鍵”,它能用于返回任何表單輸入控件的值,比如text box,drop-down list。這個(gè)方法也能用元素id或元素本身做為參數(shù)。

<script>
function test3()
{
alert( $F('userName') );
}
</script>
<input type="text" id="userName" value="Joe Doe"><br>
<input type="button" value=Test3 onclick="test3();"><br>

使用$A()函數(shù)

$A()函數(shù)能把它接收到的單個(gè)的參數(shù)轉(zhuǎn)換成一個(gè)Array對(duì)象。

這個(gè)方法,結(jié)合被本類庫擴(kuò)展了的Array類,能方便的把任何的可枚舉列表轉(zhuǎn)換成或拷貝到一個(gè)Array對(duì)象。一個(gè)推薦的用法就是把DOM Node Lists轉(zhuǎn)換成一個(gè)普通的Array對(duì)象,從而更有效率的進(jìn)行遍歷,請(qǐng)看下面的例子。

<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();" >

使用 $H() 函數(shù)

$H()函數(shù)把一些對(duì)象轉(zhuǎn)換成一個(gè)可枚舉的和聯(lián)合數(shù)組類似的Hash對(duì)象。

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

使用$R()函數(shù)

$R()是new ObjectRange(lowBound,upperBound,excludeBounds)的縮寫。

跳到ObjectRange 類文檔可以看到一個(gè)關(guān)于此類的完整描述. 此時(shí),我們還是先來看一個(gè)例子以展示這個(gè)縮寫能代替哪些方法吧。其它相關(guān)的一些知識(shí)可以在Enumerable 對(duì)象文檔中找到。

<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();" >

使用Try.these()函數(shù)

Try.these() 方法使得實(shí)現(xiàn)當(dāng)你想調(diào)用不同的方法直到其中的一個(gè)成功正常的這種需求變得非常容易, 他把一系列的方法作為參數(shù)并且按順序的一個(gè)一個(gè)的執(zhí)行這些方法直到其中的一個(gè)成功執(zhí)行,返回成功執(zhí)行的那個(gè)方法的返回值。

在下面的例子中, xmlNode.text在一些瀏覽器中好用,但是xmlNode.textContent在另一些瀏覽器中正常工作。 使用Try.these()方法我們可以得到正常工作的那個(gè)方法的返回值。

<script>
function getXmlNodeValue(xmlNode){
    return Try.these(
        function() {return xmlNode.text;},
        function() {return xmlNode.textContent;)
        );
}
</script>
  

Ajax對(duì)象

上面提到的共通方法非常好,但是面對(duì)它吧,它們不是最高級(jí)的那類東西。它們是嗎?你很可能自己編寫了這些甚至在你的腳本里面有類似功能的方法。但是這些方法只是冰山一角。

我很肯定你對(duì)prototype.js感興趣的原因很可能是由于它的AJAX能力。所以讓我們解釋當(dāng)你需要完成AJAX邏輯的時(shí)候,這個(gè)包如何讓它更容易。

Ajax 對(duì)象是一個(gè)預(yù)定義對(duì)象,由這個(gè)包創(chuàng)建,為了封裝和簡(jiǎn)化編寫AJAX 功能涉及的狡猾的代碼。 這個(gè)對(duì)象包含一系列的封裝AJAX邏輯的類。我們來看看其中幾個(gè)類。

使用Ajax.Request

如果你不使用任何的幫助程序包,你很可能編寫了整個(gè)大量的代碼來創(chuàng)建XMLHttpRequest對(duì)象并且異步的跟蹤它的進(jìn)程, 然后解析出響應(yīng) 然后處理它。當(dāng)你不需要支持多于一種類型的瀏覽器時(shí)你會(huì)感到非常的幸運(yùn)。

為了支持 AJAX 功能。這個(gè)包定義了 Ajax.Request 類。

假如你有一個(gè)應(yīng)用程序可以通過url http://yoursever/app/get_sales?empID=1234&year=1998與服務(wù)器通信。它返回下面這樣的XML 響應(yīng)。

<?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>

Ajax.Request對(duì)象和服務(wù)器通信并且得到這段XML是非常簡(jiǎn)單的。下面的例子演示了它是如何完成的。

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

你注意到傳入 Ajax.Request構(gòu)造方法的第二個(gè)對(duì)象了嗎? 參數(shù){method: 'get', parameters: pars, onComplete: showResponse} 表示一個(gè)匿名對(duì)象的真實(shí)寫法。他表示你傳入的這個(gè)對(duì)象有一個(gè)名為 method 值為 'get'的屬性,另一個(gè)屬性名為 parameters 包含HTTP請(qǐng)求的查詢字符串,和一個(gè)onComplete 屬性/方法包含函數(shù)showResponse

還有一些其它的屬性可以在這個(gè)對(duì)象里面定義和設(shè)置,如 asynchronous,可以為truefalse 來決定AJAX對(duì)服務(wù)器的調(diào)用是否是異步的(默認(rèn)值是 true)。

這個(gè)參數(shù)定義AJAX調(diào)用的選項(xiàng)。在我們的例子中,在第一個(gè)參數(shù)通過HTTP GET命令請(qǐng)求那個(gè)url,傳入了變量 pars包含的查詢字符串, Ajax.Request 對(duì)象在它完成接收響應(yīng)的時(shí)候?qū)⒄{(diào)用showResponse 方法。

也許你知道, XMLHttpRequest在HTTP請(qǐng)求期間將報(bào)告進(jìn)度情況。這個(gè)進(jìn)度被描述為四個(gè)不同階段:Loading, Loaded, Interactive, 或 Complete。你可以使 Ajax.Request 對(duì)象在任何階段調(diào)用自定義方法 ,Complete 是最常用的一個(gè)。想調(diào)用自定義的方法只需要簡(jiǎn)單的在請(qǐng)求的選項(xiàng)參數(shù)中的名為 onXXXXX 屬性/方法中提供自定義的方法對(duì)象。 就像我們例子中的 onComplete 。你傳入的方法將會(huì)被用一個(gè)參數(shù)調(diào)用,這個(gè)參數(shù)是 XMLHttpRequest 對(duì)象自己。你將會(huì)用這個(gè)對(duì)象去得到返回的數(shù)據(jù)并且或許檢查包含有在這次調(diào)用中的HTTP結(jié)果代碼的 status 屬性。

還有另外兩個(gè)有用的選項(xiàng)用來處理結(jié)果。我們可以在onSuccess 選項(xiàng)處傳入一個(gè)方法,當(dāng)AJAX無誤的執(zhí)行完后調(diào)用, 相反的,也可以在onFailure選項(xiàng)處傳入一個(gè)方法,當(dāng)服務(wù)器端出現(xiàn)錯(cuò)誤時(shí)調(diào)用。正如onXXXXX 選項(xiàng)傳入的方法一樣,這兩個(gè)在被調(diào)用的時(shí)候也傳入一個(gè)帶有AJAX請(qǐng)求的XMLHttpRequest對(duì)象。

我們的例子沒有用任何有趣的方式處理這個(gè) XML響應(yīng), 我們只是把這段XML放進(jìn)了一個(gè)文本域里面。對(duì)這個(gè)響應(yīng)的一個(gè)典型的應(yīng)用很可能就是找到其中的想要的信息,然后更新頁面中的某些元素, 或者甚至可能做某些XSLT轉(zhuǎn)換而在頁面中產(chǎn)生一些HTML。

 在1.4.0版本中,一種新的事件回傳外理被引入。如果你有一段代碼總是要為一個(gè)特殊的事件執(zhí)行,而不管是哪個(gè)AJAX調(diào)用引發(fā)它,那么你可以使用新的Ajax.Responders對(duì)象。

假設(shè)你想要在一個(gè)AJAX調(diào)用正在運(yùn)行時(shí),顯示一些提示效果,像一個(gè)不斷轉(zhuǎn)動(dòng)的圖標(biāo)之類的,你可以使用兩個(gè)全局事件Handler來做到,其中一個(gè)在第一個(gè)調(diào)用開始時(shí)顯示圖標(biāo),另一個(gè)在最后一個(gè)調(diào)用完成時(shí)隱藏圖標(biāo)。看下面的例子。

<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'><img src='spinner.gif'>Loading...</div>

更完全的解釋,請(qǐng)參照 Ajax.Request 參考Ajax選項(xiàng)參考

使用Ajax.Updater

如果你的服務(wù)器的另一端返回的信息已經(jīng)是HTML了,那么使用這個(gè)程序包中 Ajax.Updater 類將使你的生活變得更加得容易。用它你只需提供哪一個(gè)元素需要被AJAX請(qǐng)求返回的HTML填充就可以了,例子比我寫說明的更清楚。 

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

你可以看到,這段代碼比前面的例子更加簡(jiǎn)潔,不包括 onComplete 方法,但是在構(gòu)造方法中傳入了一個(gè)元素id。 我們來稍稍修改一下代碼來描述如何在客戶端處理服務(wù)器段錯(cuò)誤成為可能。

我們將加入更多的選項(xiàng), 指定處理錯(cuò)誤的一個(gè)方法。這個(gè)是用 onFailure 選項(xiàng)來完成的。我們也指定了一個(gè) placeholder 只有在成功請(qǐng)求之后才會(huì)被填充。為了完成這個(gè)目的我們修改了第一個(gè)參數(shù)從一個(gè)簡(jiǎn)單的元素id到一個(gè)帶有兩個(gè)屬性的對(duì)象, success (一切OK的時(shí)候被用到) 和 failure (有地方出問題的時(shí)候被用到) 在下面的例子中沒有用到failure屬性,而僅僅在 onFailure 處使用了 reportError 方法。

<script>
function getHTML()
{
var url = 'http://yourserver/app/getSomeHTML';
var pars = 'someParameter=ABC';

var myAjax = new Ajax.Updater( {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 id="placeholder"></div>

如果你的服務(wù)器邏輯是連同HTML 標(biāo)記返回JavaScript 代碼, Ajax.Updater對(duì)象可以執(zhí)行那段JavaScript代碼。為了使這個(gè)對(duì)象對(duì)待響應(yīng)為JavaScript,你只需在最后參數(shù)的對(duì)象構(gòu)造方法中簡(jiǎn)單加入evalScripts: true屬性。但是值得提醒的是,像這個(gè)選項(xiàng)名evalScripts暗示的,這些腳本會(huì)被執(zhí)行,但是它們不會(huì)被加入到Page的腳本中。“有什么區(qū)別?”,可能你會(huì)這樣問。我們假定請(qǐng)求地址返回的東東像這樣:

<script language="javascript" type="text/javascript">
function sayHi(){
alert('Hi');
}
</script>
<input type=button value="Click Me" onclick="sayHi()">

如果你以前這樣嘗試過,你知道這些腳本不會(huì)如你所期望的那樣工作,原因是這段腳本會(huì)被執(zhí)行,但像上面這樣的腳本執(zhí)行并不會(huì)創(chuàng)建一個(gè)名叫sayHi的函數(shù),它什么也不做。如果要?jiǎng)?chuàng)建一個(gè)函數(shù),我們應(yīng)當(dāng)把代碼改成下面這個(gè)樣子:

<script language="javascript" type="text/javascript">
sayHi = function(){
alert('Hi');
};
</script> <input type=button value="Click Me" onclick="sayHi()">

為什么我們?cè)谏厦娴拇a中不使用var關(guān)鍵字來聲明這個(gè)變量呢(指sayHi ),因?yàn)槟菢幼鰟?chuàng)建出來的函數(shù)將只是當(dāng)前腳本塊的一個(gè)局部變量(至少在IE中是這樣)。不寫var關(guān)鍵字,創(chuàng)建出來的對(duì)象的作用域就是我們所期望的window。

更多相關(guān)知識(shí),請(qǐng)參看  Ajax.Updater referenceoptions reference.

枚舉... 噢!噢!

你知道,我們都是這樣來做循環(huán)的,建一個(gè)Array,用elements組織它們,再建一個(gè)循環(huán)結(jié)構(gòu)(例如for,foreach,while)通過index數(shù)字來訪問每一個(gè)element,再用這個(gè)element做一些動(dòng)作。

當(dāng)你想到這時(shí),你會(huì)發(fā)現(xiàn)幾乎每次寫循環(huán)代碼你都會(huì)遲早用到一個(gè)Array。那么,如果Array對(duì)象能夠提供更多的功能給它們的迭代器使用不是很爽嗎?確實(shí)是這樣,事實(shí)上很多的編程語言都在它們的Array或其它類似的結(jié)構(gòu)中(如Collections,Lists)提供一些這樣的功能。

現(xiàn)在好了,prototype.js了給我們一個(gè) Enumerable對(duì)象,它實(shí)現(xiàn)了很多和可迭代數(shù)據(jù)進(jìn)行交互的竅門。和原有的JS對(duì)象相比prototype.js更上一層樓,它對(duì)Array 類s擴(kuò)展了所有枚舉要用的函數(shù)。

循環(huán), Ruby樣式的

在標(biāo)準(zhǔn)的javascript中,如果你想把一個(gè)array中的所有elements顯示出來,你可以像下面代碼這樣寫得很好:

<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();" >

使用我們新的最好的朋友,prototype.js,我們可以把它生寫成這樣

      function showList(){
var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];
simpsons.each( function(familyMember){
alert(familyMember);
});
}

你可能會(huì)想“非常奇怪的方式...相對(duì)舊的,這種語法太怪異了”。哦,在上面的例子,確實(shí)什么也沒有,在這個(gè)簡(jiǎn)單得要死例子中,也沒有改變太多啊,盡管如此,請(qǐng)繼續(xù)讀下去。

在繼續(xù)下面內(nèi)容之前,你注意到那個(gè)被做為一個(gè)參數(shù)傳遞給each函數(shù)的函數(shù)?我們把它理解成迭代器函數(shù)。

Your arrays on steroids

就如我們上面提到的,把你的Array中的elements當(dāng)成相同的類型使用相同的屬性和函數(shù)是很通用(Common,不知該翻譯成通用還是庸俗)的。讓我們看看怎么樣利用我們新的馬力強(qiáng)勁的Arrays的迭代功能吧。

依照標(biāo)準(zhǔn)找到一個(gè)element。

 

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

現(xiàn)在我們?cè)傧乱怀牵纯慈绾芜^濾一個(gè)Array中的元素,從每個(gè)元素中得到我們想要的成員。

 

<script>
function showLocalLinks(paragraph){
paragraph = $(paragraph);
var links = $A(paragraph.getElementsByTagName('a'));
//find links that do not start with 'http'
var localLinks = links.findAll( function(link){
var start = link.href.substring(0,4);
return start !='http';
});
//now the link texts
var texts = localLinks.pluck('innerHTML');
//get them in a single string
var result = texts.inspect();
alert(result);
}
</script>
<p id="someText">
This <a >text</a> has
a <a href="#localAnchor">lot</a> of
<a href="#otherAnchor">links</a>. Some are
<a >external</a>
and some are <a href="#someAnchor">local</a>
</p>
<input type=button value="Find Local Links" onclick="showLocalLinks('someText')">

上面的代碼僅僅是一點(diǎn)小小的實(shí)踐讓人愛上這種語法。請(qǐng)參看 EnumerableArray的所有函數(shù)


 

prototype.js參考

JavaScript類擴(kuò)展

prototype.js 類庫實(shí)現(xiàn)強(qiáng)大功能的一種途徑是擴(kuò)展已有的JavaScript 類。

對(duì) Object的擴(kuò)展

Method Kind Arguments Description
extend(destination, source) static destination: any object, source: any object 提供一種通過拷貝所有源以象屬性和函數(shù)到目標(biāo)函數(shù)實(shí)現(xiàn)繼承的方法
inspect(targetObj) static targetObj: any object 返回可讀性好關(guān)于目標(biāo)對(duì)象的文字描述,如果對(duì)象實(shí)例沒有定義一個(gè)inspect函數(shù),默認(rèn)返回toString函數(shù)的值。

對(duì)Number的擴(kuò)展

Method Kind Arguments Description
toColorPart() instance (none) 返回?cái)?shù)字的十六進(jìn)制表示形式。在把一個(gè)RGB數(shù)字轉(zhuǎn)換成HTML表現(xiàn)形式時(shí)很有用。
succ() instance (none)  返回下一個(gè)數(shù)字,這個(gè)方法可用于迭代調(diào)用場(chǎng)景中。
times(iterator) instance iterator: a function object conforming to Function(index) Calls the iterator function repeatedly passing the current index in the index argument. 反復(fù)調(diào)用iterator函數(shù)并傳遞當(dāng)前index到iterator的index參數(shù)。

下面的例子用提示框顯示0-9。

<script>
function demoTimes(){
var n = 10;
n.times(function(index){
alert(index);
});
/***************************
* you could have also used:
* (10).times( .... );
***************************/
}
</script>
<input type=button value="Test Number.times()" onclick="demoTimes()">

對(duì) Function擴(kuò)展

Method Kind Arguments Description
bind(object) instance object: the object that owns the method 返回function的實(shí)例,這個(gè)實(shí)例和源function的結(jié)構(gòu)一樣,但是它已被綁定給了參數(shù)中提供的object,就是說,function中的this指針指向參數(shù)object。
bindAsEventListener(object) instance object: the object that owns the method 用法和上面的bind一樣,區(qū)別在于用來綁定事件。

讓我們看看如何運(yùn)用這些擴(kuò)展。

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

對(duì)String的擴(kuò)展

Method Kind Arguments Description
stripTags() instance (none) 返回一個(gè)把所有的HTML或XML標(biāo)記都移除的字符串。
stripScripts() instance (none) 返回一個(gè)把所有的script都移除的字符串。
escapeHTML() instance (none) 返回一個(gè)把所有的HTML標(biāo)記合適的轉(zhuǎn)義掉的字符串。
unescapeHTML() instance (none) escapeHTML()的反轉(zhuǎn)。
extractScripts() instance (none) 返回一個(gè)包含在string中找到的所有<script>的數(shù)組。
evalScripts() instance (none) 執(zhí)行在string中找到的所有<script>。
toQueryParams() instance (none) 把querystring分割才一個(gè)用parameter name做index的聯(lián)合Array,更像一個(gè)hash。
parseQuery() instance (none) 和toQueryParams()一樣.
toArray() instance (none) 把字符串轉(zhuǎn)換成字符數(shù)組.
camelize() instance (none) 轉(zhuǎn)換一個(gè)以連字符連接的字符串成一個(gè)駱駝法樣式的字符串。比如,這個(gè)函數(shù)在寫代碼時(shí),把它做為一個(gè)樣式工具使用是很有用的。

對(duì)  Array的擴(kuò)展

因?yàn)閍rray擴(kuò)展于enumerable,所以所有enumberable對(duì)象的函數(shù),array都是可以使用的,除此之外,下面的這些也是已經(jīng)實(shí)現(xiàn)了的。

Method Kind Arguments Description
clear() instance (none) 清空。
compact() instance (none) 返回一個(gè)不包括源array中null或undefined元素的array,此方法不改變?cè)碼rray。
first() instance (none) 返回array的第一個(gè)對(duì)象。
flatten() instance (none) 通過遞歸組合array每個(gè)元素的子元素(如果該元素也是array)來返回一個(gè)“扁平的”一維的array。
indexOf(value) instance value: what you are looking for. 返回給出數(shù)字位置(從0算起)的元素,如果在該位置沒有找到對(duì)象,返回-1。
inspect() instance (none) 重載inspect(),返回更好格式的反映Array每個(gè)元素的字符描述。
last() instance (none) 返回最后一個(gè)元素。
reverse([applyToSelf]) instance applyToSelf: indicates if the array itself should also be reversed.  反轉(zhuǎn)Array中元素的順序,如果沒有給出參數(shù),或參數(shù)為true,則源Array中元素的順序也反轉(zhuǎn),否則源Array保持不變。
shift() instance (none) 返回Array的第一個(gè)元素并從Array中移除它,Array的Length-1。
without(value1 [, value2 [, .. valueN]]) instance value1 ... valueN: values to be excluded if present in the array.  返回一個(gè)把參數(shù)列表中包含的元素從源Array中排除的Array。

document DOM擴(kuò)展

Method Kind Arguments Description
getElementsByClassName(className [, parentElement]) instance className: name of a CSS class associated with the elements, parentElement: object or id of the element that contains the elements being retrieved. 返回所有CSS className屬性等于className參數(shù)的元素,如果沒有給出parentElement,那么將搜索document body。(此處使用document.body我覺得不如使用document,因?yàn)橛袝r(shí)有的頁面沒有body) 

Event擴(kuò)展

Property Type Description
KEY_BACKSPACE NumberNumber 8: Constant. Code for the Backspace key.
KEY_TAB Number 9: Constant. Code for the Tab key.
KEY_RETURN Number 13: Constant. Code for the Return key.
KEY_ESC Number 27: Constant. Code for the Esc key.
KEY_LEFT Number 37: Constant. Code for the Left arrow key.
KEY_UP Number 38: Constant. Code for the Up arrow key.
KEY_RIGHT Number 39: Constant. Code for the Right arrow key.
KEY_DOWN Number 40: Constant. Code for the Down arrow key.
KEY_DELETE Number 46: Constant. Code for the Delete key.
observers: Array List of cached observers. Part of the internal implementation details of the object.

Method Kind Arguments Description
element(event) static event: an Event object 返回事件源對(duì)象。
isLeftClick(event) static event: an Event object 如果點(diǎn)擊了鼠標(biāo)左鍵,返回true.
pointerX(event) static event: an Event object 返回鼠標(biāo)的X座標(biāo)。
pointerY(event) static event: an Event object 返回鼠標(biāo)的Y座標(biāo)。
stop(event) static event: an Event object 使用此函數(shù)來中斷事件的默認(rèn)行為并阻止傳遞(冒泡)。
findElement(event, tagName) static event: an Event object, tagName: name of the desired tag. 從事件源對(duì)象開始向上搜索DOM樹,直到找到第一個(gè)符合tagName的元素
observe(element, name, observer, useCapture) static element: object or id, name: event name (like 'click', 'load', etc), observer: function to handle the event, useCapture: if true, handles the event in the capture phase and if false in the bubbling phase. 為對(duì)象的某個(gè)事件增加一個(gè)處理函數(shù)。
stopObserving(element, name, observer, useCapture) static element: object or id, name: event name (like 'click'), observer: function that is handling the event, useCapture: if true handles the event in the capture phase and if false in the bubbling phase. 和上面的函數(shù)相反。
_observeAndCache(element, name, observer, useCapture) static   私有函數(shù),別管它。
unloadCache() static (none) 私有函數(shù),別管它。從內(nèi)存中清除所有的observers緩存。

下面代碼演示如何給window添加一個(gè)load事件處理函數(shù)。

<script>
Event.observe(window, 'load', showMessage, false); function showMessage() { alert('Page loaded.'); } </script>

在prototype.js中定義新的對(duì)象和類

另一個(gè)這個(gè)程序包幫助你的地方就是提供許多既支持面向?qū)ο笤O(shè)計(jì)理念又有共通功能的許多對(duì)象。

The PeriodicalExecuter object

這個(gè)對(duì)象提供一定間隔時(shí)間上重復(fù)調(diào)用一個(gè)方法的邏輯。

Method Kind Arguments Description
[ctor](callback, interval) constructor callback: a parameterless function, interval: number of seconds 創(chuàng)建這個(gè)對(duì)象的實(shí)例將會(huì)重復(fù)調(diào)用給定的方法。

Property Type Description
callback Function() 被調(diào)用的方法,該方法不能傳入?yún)?shù)。
frequency Number 以秒為單位的間隔。
currentlyExecuting Boolean 表示這個(gè)方法是否正在執(zhí)行。

The Prototype object

Prototype 沒有太重要的作用,只是聲明了該程序包的版本 。

Property Type Description
Version String 版本。
emptyFunction Function() 空函數(shù)。
K Function(obj) 一個(gè)僅僅回傳參數(shù)的函數(shù)。
ScriptFragment String 識(shí)別script的正則式。

The Enumerable object

Enumberable對(duì)象能夠已更優(yōu)雅的方式實(shí)現(xiàn)對(duì)列表樣式的結(jié)構(gòu)進(jìn)行枚舉。

很多其它的對(duì)象通過擴(kuò)展自Enumberable對(duì)象來得到這些有用的接口。

Method Kind Arguments Description
each(iterator) instance iterator: a function object conforming to Function(value, index) 把每個(gè)element做為第一個(gè)參數(shù),element的index作為第一個(gè)參數(shù)調(diào)用iterator函數(shù)。
all([iterator]) instance iterator: a function object conforming to Function(value, index) 這個(gè)函數(shù)會(huì)用給出的iterator測(cè)試整個(gè)集合,如果集合中任一元素在iterator函數(shù)測(cè)試中返回false或null,那么這個(gè)函數(shù)返回false,否則返回true。如果沒有給出iterator,那么就會(huì)測(cè)試所有的元素是不是不等于false和null。你可以簡(jiǎn)單的把它看成是“檢測(cè)每個(gè)元素都為非空非負(fù)”。
any(iterator) instance iterator: a function object conforming to Function(value, index), optional. 這個(gè)函數(shù)會(huì)用給出的iterator測(cè)試整個(gè)集合,如果集合中任一元素在iterator函數(shù)測(cè)試中返回true,那么這個(gè)函數(shù)返回true,否則返回false。如果沒有給出iterator,那么就會(huì)測(cè)試所有的元素是不是有一個(gè)不等于false和null。你可以簡(jiǎn)單的把它看成是“檢測(cè)元素中是不是有非空非負(fù)的”。
collect(iterator) instance iterator: a function object conforming to Function(value, index)  調(diào)用iterator函數(shù)根據(jù)集合中每個(gè)元素返回一個(gè)結(jié)果,然后按照原來集合中的順序,返回一個(gè)Array。
detect(iterator) instance iterator: a function object conforming to Function(value, index) 集合中每個(gè)元素調(diào)用一次Iterator,返回第一個(gè)使Iterator返回True的元素,如果最終都沒有為true的調(diào)用,那么返回null。
entries() instance (none) 等于toArray().
find(iterator) instance iterator: a function object conforming to Function(value, index) 等于 detect().
findAll(iterator) instance iterator: a function object conforming to Function(value, index) 集合中每個(gè)元素調(diào)用Iterator,返回一個(gè)由所有調(diào)用Iterator返回結(jié)果等于true的元素組成的數(shù)組。和reject()相反。
grep(pattern [, iterator]) instance pattern: a RegExp object used to match the elements, iterator: a function object conforming to Function(value, index)  用pattern參數(shù)正則表達(dá)式測(cè)試集合中的每個(gè)元素,返回一個(gè)包含所有匹配正則式的元素的Array,如果給出了Iterator,那個(gè)每個(gè)結(jié)果還要經(jīng)過一下Iterator處理。
include(obj) instance obj: any object  判斷集合中包不包含指定對(duì)象。
inject(initialValue, iterator) instance initialValue: any object to be used as the initial value, iterator: a function object conforming to Function(accumulator, value, index)  用Iterator聯(lián)接所有集合中的元素。Iterator在被調(diào)用時(shí)把上一次迭代的結(jié)果做為第一個(gè)參數(shù)傳給accumulator。第一次迭代時(shí),accurmelator等于initialValue,最后返回accumulator的值。
invoke(methodName [, arg1 [, arg2 [...]]]) instance methodName: name of the method that will be called in each element, arg1..argN: arguments that will be passed in the method invocation. 集合中的每個(gè)元素調(diào)用指定的函數(shù)(查看源代碼可以發(fā)現(xiàn)指定函數(shù)被調(diào)用時(shí),this指針被傳成當(dāng)前元素),并傳入給出的參數(shù),返回調(diào)用結(jié)果組成的Array。
map(iterator) instance iterator: a function object conforming to Function(value, index) 同collect().
max([iterator]) instance iterator: a function object conforming to Function(value, index) 返回集合中元素的最大值,或調(diào)用Iterator后返回值的最大值(如果給出了Iterator的話)。
member(obj) instance obj: any object include().
min([iterator]) instance iterator: a function object conforming to Function(value, index) 返回最小值,參見max()。
partition([iterator]) instance iterator: a function object conforming to Function(value, index) 返回一個(gè)包含兩個(gè)Array的Array,第一個(gè)Array包含所有調(diào)用Iterator返回True的元素,第二個(gè)Array包含剩下的元素。如果Iterator沒有給出,那么就根據(jù)元素本身判斷。
pluck(propertyName) instance propertyName name of the property that will be read from each element. This can also contain the index of the element 返回每個(gè)元素的指定屬性名的屬性的值組成的Array。
reject(iterator) instance iterator: a function object conforming to Function(value, index) 和  findAll()相反(返回所有等于false的元素).
select(iterator) instance iterator: a function object conforming to Function(value, index) findAll().
sortBy(iterator) instance iterator: a function object conforming to Function(value, index) 根據(jù)每個(gè)元素調(diào)用Iterator返回的值進(jìn)行排序返回一個(gè)Array。
toArray() instance (none) 返回由集合所有元素組成的一個(gè)Array。
zip(collection1[, collection2 [, ... collectionN [,transform]]]) instance collection1 .. collectionN: enumerations that will be merged, transform: a function object conforming to Function(value, index) 合并每個(gè)給出的集合到當(dāng)前集合。合并操作返回一個(gè)新的array,這個(gè)array的元素個(gè)數(shù)和原集合的元素個(gè)數(shù)一樣,這個(gè)array的每個(gè)元素又是一個(gè)子array,它合并了所有集合中相同index的元素。如果transform函數(shù)被指定,那么array的每個(gè)元素還會(huì)調(diào)用transform函數(shù)先做處理。舉個(gè)例子: [1,2,3].zip([4,5,6], [7,8,9]).inspect() 返回 "[ [1,4,7],[2,5,8],[3,6,9] ]"

The Hash object

 Hash對(duì)象實(shí)現(xiàn)一種Hash結(jié)構(gòu),也就是一個(gè)Key:Value對(duì)的集合。

Hash中的每個(gè)Item是一個(gè)有兩個(gè)元素的array,前一個(gè)是Key,后一個(gè)是Value,每個(gè)Item也有兩個(gè)不需加以說明的屬性,key和value。

Method Kind Arguments Description
keys() instance (none) 返回所有Item的key的集合的一個(gè)array。
values() instance (none) 返回所有Item的value的集合的一個(gè)array。
merge(otherHash) instance otherHash: Hash object 合并給出的Hash,返回一個(gè)新Hash。
toQueryString() instance (none) 以QueryString那樣的樣式返回hash中所有的item,例如: 'key1=value1&key2=value2&key3=value3'
inspect() instance (none) 用一種合適的方法顯示hash中的key:value對(duì)。

The ObjectRange class

繼承自  Enumerable

用上、下邊界描述一個(gè)對(duì)象區(qū)域。

Property Type Kind Description
start (any) instance

range的下邊界

end (any) instance range的上邊界
exclusive Boolean instance 決定邊界自身是不是range的一部分。

Method Kind Arguments Description
[ctor](start, end, exclusive) constructor start: the lower bound, end: the upper bound, exclusive: include the bounds in the range? 創(chuàng)建一個(gè)range對(duì)象,從start生成到end,這里要注意的是,start和end必段類型一致,而且該類型要有succ()方法。
include(searchedValue) instance searchedValue: value that we are looking for 檢查一個(gè)value是不是在range中。

The Class object

在這個(gè)程序包中 Class 對(duì)象在聲明其他的類時(shí)候被用到 。用這個(gè)對(duì)象聲明類使得新類支持 initialize() 方法,他起構(gòu)造方法的作用。

看下面的例子

//declaring the class
var MySampleClass = Class.create();

//defining the rest of the class implmentation
MySampleClass.prototype = {

   initialize: function(message) {
this.message = message;
   },

   showMessage: function(ajaxResponse) {
      alert(this.message);
   }
};

//now, let's instantiate and use one object
var myTalker = new MySampleClass('hi there.');
myTalker.showMessage(); //displays alert

Method Kind Arguments Description
create(*) instance (any) 定義新類的構(gòu)造方法。

The Ajax object

這個(gè)對(duì)象被用作其他提供AJAX功能的類的根對(duì)象。 

Property Type Kind Description
activeRequestCount Number instance 正在處理中的Ajax請(qǐng)求的個(gè)數(shù)。

Method Kind Arguments Description
getTransport() instance (none) 返回新的XMLHttpRequest 對(duì)象。

The Ajax.Responders object

繼承自 Enumerable

這個(gè)對(duì)象維持一個(gè)在Ajax相關(guān)事件發(fā)生時(shí)將被調(diào)用的對(duì)象的列表。比如,你要設(shè)置一個(gè)全局鉤子來處理Ajax操作異常,那么你就可以使用這個(gè)對(duì)象。

Property Type Kind Description
responders Array instance 被注冊(cè)到Ajax事件通知的對(duì)象列表。

Method Kind Arguments Description
register(responderToAdd) instance responderToAdd: object with methods that will be called. 被傳入?yún)?shù)的對(duì)象應(yīng)包含名如Ajax事件的系列方法(如onCreate,onComplete,onException)。通訊事件引發(fā)所有被注冊(cè)的對(duì)象的合適名稱的函數(shù)被調(diào)用。
unregister(responderToRemove) instance responderToRemove: object to be removed from the list.  從列表中移除。
dispatch(callback, request, transport, json) instance callback: name of the AJAX event being reported, request: the Ajax.Request object responsible for the event, transport: the XMLHttpRequest object that carried (or is carrying) the AJAX call, json: the X-JSON header of the response (if present) 遍歷被注冊(cè)的對(duì)象列表,找出有由callback參數(shù)決定的那個(gè)函數(shù)的對(duì)象。然后向這些函數(shù)傳遞其它的三個(gè)參數(shù),如果Ajax響應(yīng)中包含一個(gè)含有JSON內(nèi)容的X-JSON HTTP頭,那么它會(huì)被熱行并傳入json參數(shù)。如果事件是onException,那么transport參數(shù)會(huì)被異常代替,json不會(huì)傳遞。

The Ajax.Base class

這個(gè)類是其他在Ajax對(duì)象中定義的類的基類。

Method Kind Arguments Description
setOptions(options) instance options: AJAX options 設(shè)定AJAX操作想要的選項(xiàng)。
responseIsSuccess() instance (none) 返回 true 如果AJAX操作成功,否則為 false
responseIsFailure() instance (none) responseIsSuccess() 相反。

The Ajax.Request class

繼承自 Ajax.Base

封裝 AJAX 操作

Property Type Kind Description
Events Array static 在AJAX操作中所有可能報(bào)告的事件/狀態(tài)的列表。這個(gè)列表包括: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'
transport XMLHttpRequest instance 承載AJAX操作的 XMLHttpRequest 對(duì)象。
url string instance 請(qǐng)求的URL。

Method Kind Arguments Description
[ctor](url, options) constructor url: the url to be fetched, options: AJAX options 創(chuàng)建這個(gè)對(duì)象的一個(gè)實(shí)例,它將在給定的選項(xiàng)下請(qǐng)求url。onCreate事件在調(diào)用constructor事被激發(fā)。 重要: 如果選擇的url受到瀏覽器的安全設(shè)置,他會(huì)一點(diǎn)作用也不起。 很多情況下,瀏覽器不會(huì)請(qǐng)求與當(dāng)前頁面不同主機(jī)(域名)的url。 你最好只使用本地url來避免限制用戶配置他們的瀏覽器(謝謝Clay)
evalJSON() instance (none) 這個(gè)方法顯然不會(huì)被外部調(diào)用。它在Ajax響應(yīng)中含有X-JSON HTTP頭時(shí)用于內(nèi)部調(diào)用執(zhí)行這些內(nèi)容。
evalReponse() instance (none) 這也方法顯然不會(huì)被外部調(diào)用,如果Ajax響應(yīng)含有一個(gè)值為text/javascript的Cotent-Type頭,那么這個(gè)方法就用被調(diào)用執(zhí)行響應(yīng)體。
header(name) instance name: HTTP header name 引用Ajax響應(yīng)的頭的內(nèi)容,在Ajax訪問結(jié)束后再調(diào)用這個(gè)方法。
onStateChange() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 當(dāng)AJAX請(qǐng)求狀態(tài)改變的時(shí)候被這個(gè)對(duì)象自己調(diào)用。
request(url) instance url: url for the AJAX call 這個(gè)方法通常不會(huì)被外部調(diào)用。已經(jīng)在構(gòu)造方法中調(diào)用了。
respondToReadyState(readyState) instance readyState: state number (1 to 4) 這個(gè)方法通常不會(huì)被外部調(diào)用。 當(dāng)AJAX請(qǐng)求狀態(tài)改變的時(shí)候被這個(gè)對(duì)象自己調(diào)用。
setRequestHeaders() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 被這個(gè)對(duì)象自己調(diào)用來配置在HTTP請(qǐng)求要發(fā)送的HTTP報(bào)頭。

The options argument object

An important part of the AJAX operations is the options argument. There's no options class per se. Any object can be passed, as long as it has the expected properties. It is common to create anonymous objects just for the AJAX calls.

Property Type Default Description
method String 'post' HTTP 請(qǐng)求方式。
parameters String '' 在HTTP請(qǐng)求中傳入的url格式的值列表。
asynchronous Boolean true 指定是否做異步 AJAX 請(qǐng)求。
postBody String undefined 在HTTP POST的情況下,傳入請(qǐng)求體中的內(nèi)容。
requestHeaders Array undefined 和請(qǐng)求一起被傳入的HTTP頭部列表, 這個(gè)列表必須含有偶數(shù)個(gè)項(xiàng)目, 任何奇數(shù)項(xiàng)目是自定義的頭部的名稱, 接下來的偶數(shù)項(xiàng)目使這個(gè)頭部項(xiàng)目的字符串值。 例子:['my-header1', 'this is the value', 'my-other-header', 'another value']
onXXXXXXXX Function(XMLHttpRequest, Object) undefined 在AJAX請(qǐng)求中,當(dāng)相應(yīng)的事件/狀態(tài)形成的時(shí)候調(diào)用的自定義方法。 例如 var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. 這個(gè)方法將被傳入一個(gè)參數(shù), 這個(gè)參數(shù)是承載AJAX操作的 XMLHttpRequest 對(duì)象,另一個(gè)是包含被執(zhí)行X-JSON響應(yīng)HTTP頭。
onSuccess Function(XMLHttpRequest, Object) undefined 當(dāng)AJAX請(qǐng)求成功完成的時(shí)候調(diào)用的自定義方法。 這個(gè)方法將被傳入一個(gè)參數(shù), 這個(gè)參數(shù)是承載AJAX操作的 XMLHttpRequest 對(duì)象,另一個(gè)是包含被執(zhí)行X-JSON響應(yīng)HTTP頭。
onFailure Function(XMLHttpRequest, Object) undefined 當(dāng)AJAX請(qǐng)求完成但出現(xiàn)錯(cuò)誤的時(shí)候調(diào)用的自定義方法。這個(gè)方法將被傳入一個(gè)參數(shù), 這個(gè)參數(shù)是承載AJAX操作的 XMLHttpRequest 對(duì)象,另一個(gè)是包含被執(zhí)行X-JSON響應(yīng)HTTP頭。
onException Function(Ajax.Request, exception) undefined 當(dāng)一個(gè)在客戶端執(zhí)行的Ajax發(fā)生像無效響應(yīng)或無效參數(shù)這樣的異常情況時(shí)被調(diào)用的自定義函數(shù)。它收到兩個(gè)參數(shù),包含異常Ajax操作的Ajax.Request對(duì)象和異常對(duì)象。
insertion an Insertion class undefined 一個(gè)能決定怎么樣插入新內(nèi)容的類,能 Insertion.Before, Insertion.Top, Insertion.Bottom, 或 Insertion.After. 只能應(yīng)用于Ajax.Updater 對(duì)象.
evalScripts Boolean undefined, false 決定當(dāng)響應(yīng)到達(dá)的時(shí)候是否執(zhí)行其中的腳本塊,只在 Ajax.Updater 對(duì)象中應(yīng)用。
decay Number undefined, 1 決定當(dāng)最后一次響應(yīng)和前一次響應(yīng)相同時(shí)在 Ajax.PeriodicalUpdater 對(duì)象中的減漫訪問的次數(shù), 例如,如果設(shè)為2,后來的刷新和之前的結(jié)果一樣, 這個(gè)對(duì)象將等待2個(gè)設(shè)定的時(shí)間間隔進(jìn)行下一次刷新, 如果又一次一樣, 那么將等待4次,等等。 不設(shè)定這個(gè)只,或者設(shè)置為1,將避免訪問頻率變慢。
frequency Number undefined, 2 用秒表示的刷新間的間隔,只能應(yīng)用于 Ajax.PeriodicalUpdater  對(duì)象。

The Ajax.Updater class

繼承自 Ajax.Request

當(dāng)請(qǐng)求的url返回一段HTML而你想把它直接放置到頁面中一個(gè)特定的元素的時(shí)候被用到。 如果url的返回<script> 的塊并且想在接收到時(shí)就執(zhí)行它的時(shí)候也可以使用該對(duì)象。含有腳本的時(shí)候使用 evalScripts 選項(xiàng)。

Property Type Kind Description
containers Object instance 這個(gè)對(duì)象包含兩個(gè)屬性:AJAX請(qǐng)求成功執(zhí)行的時(shí)候用到 containers.success , 否則的話用到 containers.failure

Method Kind Arguments Description
[ctor](container, url, options) constructor container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options 創(chuàng)建一個(gè)用給定的選項(xiàng)請(qǐng)求給定的url的一個(gè)實(shí)例。
updateContent() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 當(dāng)響應(yīng)到達(dá)的時(shí)候,被這個(gè)對(duì)象自己調(diào)用。 它會(huì)用HTML更新適當(dāng)?shù)脑鼗蛘哒{(diào)用在 insertion 選項(xiàng)中傳入的方法-這個(gè)方法將被傳入兩個(gè)參數(shù), 被更新的元素和響應(yīng)文本。

The Ajax.PeriodicalUpdater class

繼承自Ajax.Base

這個(gè)類重復(fù)生成并使用 Ajax.Updater 對(duì)象來刷新頁面中的一個(gè)元素。或者執(zhí)行 Ajax.Updater 可以執(zhí)行的其它任務(wù)。更多信息參照 Ajax.Updater 參考

Property Type Kind Description
container Object instance 這個(gè)值將直接傳入Ajax.Updater的構(gòu)造方法。
url String instance 這個(gè)值將直接傳入Ajax.Updater的構(gòu)造方法。
frequency Number instance 兩次刷新之間的間隔 (不是頻率) ,以秒為單位。 默認(rèn)2秒。 This 當(dāng)調(diào)用 Ajax.Updater 對(duì)象的時(shí)候,這個(gè)數(shù)將和當(dāng)前的 decay 相乘。
decay Number instance 重負(fù)執(zhí)行任務(wù)的時(shí)候保持的衰敗水平。
updater Ajax.Updater instance 最后一次使用的 Ajax.Updater 對(duì)象
timer Object instance 通知對(duì)象該下一次更新時(shí)用到的JavaScript 計(jì)時(shí)器。

Method Kind Arguments Description
[ctor](container, url, options) constructor container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options 創(chuàng)建一個(gè)用給定的選項(xiàng)請(qǐng)求給定的url的一個(gè)實(shí)例。
start() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 對(duì)象為了開始周期性執(zhí)行任務(wù)的時(shí)候調(diào)用的方法。
stop() instance (none) 使對(duì)象停止執(zhí)行周期任務(wù)。停止后,如果有onComplete選項(xiàng),那么引發(fā)callback。
updateComplete() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 被當(dāng)前的 Ajax.Updater 使用,當(dāng)一次請(qǐng)求結(jié)束的時(shí)候,它被用作計(jì)劃下一次請(qǐng)求。
onTimerEvent() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。當(dāng)?shù)较乱淮胃聲r(shí)被內(nèi)部調(diào)用。

The Element object

這個(gè)對(duì)象提供在操作DOM中元素時(shí)使用的功能性方法。

Method Kind Arguments Description
addClassName(element, className) instance element: element object or id, className: name of a CSS class 將給出的className添加到對(duì)象的className屬性中。
classNames(element) instance element: element object or id 返回一個(gè)Element.ClassName的對(duì)象表示CSS 給出對(duì)象有的class names。
cleanWhitespace(element) instance element: element object or id 清除對(duì)象子元素中所有空白的text node。
empty(element) instance element: element object or id 返回一個(gè)布爾值指示對(duì)象為空或只有空白字符。
getDimensions(element) instance element: element object or id 返回對(duì)象的尺寸,返回值有兩個(gè)屬性,height和width。
getHeight(element) instance element: element object or id 返回元素的 offsetHeight
getStyle(element, cssProperty) instance element: element object or id, cssProperty name of a CSS property (either format 'prop-name' or 'propName' works). 返回給定對(duì)象的CSS屬性值或沒有指定cssProperty時(shí)返回null。
hasClassName(element, className) instance element: element object or id, className: name of a CSS class 返回 true 如果元素的類名中含有給定的類名
hide(elem1 [, elem2 [, elem3 [...]]]) instance elemN: element object or id 通過設(shè)定style.display'none'來隱藏每個(gè)傳入的元素。
makeClipping(element) instance element: element object or id 能過設(shè)定overflow的值設(shè)定內(nèi)容溢出剪輯。
makePositioned(element) instance element: element object or id 更改對(duì)象的style.position為'relative'。
remove(element) instance element: element object or id 從document對(duì)象中刪除指定的元素。
removeClassName(element, className) instance element: element object or id, className: name of a CSS class 從元素的類名中刪除給定的類名。
scrollTo(element) instance element: element object or id 滾動(dòng)window到對(duì)象的位置。
setStyle(element, cssPropertyHash) instance element: element object or id, cssPropertyHash Hash object with the styles to be applied. 依照cssPropertyHash參數(shù)給對(duì)象設(shè)置CSS屬性值。
show(elem1 [, elem2 [, elem3 [...]]]) instance elemN: element object or id 用設(shè)定它的 style.display ''來顯示每個(gè)傳入的元素。
toggle(elem1 [, elem2 [, elem3 [...]]]) instance elemN: element object or id 切換每一個(gè)傳入元素的可視性。
undoClipping(element) instance element: element object or id style.overflow的值返回上一個(gè)設(shè)定值。
undoPositioned(element) instance element: element object or id 清除對(duì)象的 style.position''
update(element, html) instance element: element object or id, html: html content 用給出的HTML參數(shù)替換對(duì)象的innerHTML,如果HTML參數(shù)中包含<script>,那么它們不會(huì)被包含進(jìn)去,但是會(huì)執(zhí)行。
visible(element) instance element: element object or id 返回一個(gè)布爾值指示對(duì)象可不可見。

The Element.ClassNames class

繼承自  Enumerable

在一個(gè)對(duì)象中表示CSS class names的集合。

Method Kind Arguments Description
[ctor](element) constructor element: any DOM element object or id 創(chuàng)建一個(gè)對(duì)象,給出對(duì)象的CSS class names被表現(xiàn)在這個(gè)ClassNames對(duì)象中。
add(className) instance className: a CSS class name 把CSS class name包含進(jìn)對(duì)象的class names 列表。
remove(className) instance className: a CSS class name 從對(duì)象的class names列表中移除className
set(className) instance className: a CSS class name 設(shè)定對(duì)象CSS class name為className,移除其它c(diǎn)lass names。

The Abstract object

這個(gè)對(duì)象是這個(gè)程序包中其他類的根。它沒有任何屬性和方法。在這個(gè)對(duì)象中定義的類可以被視為傳統(tǒng)的抽象類。

The Abstract.Insertion class

這個(gè)類被用作其他提供動(dòng)態(tài)內(nèi)容插入功能的類的基類,它像一個(gè)抽象類一樣被使用。

Method Kind Arguments Description
[ctor](element, content) constructor element: element object or id, content: HTML to be inserted 創(chuàng)建一個(gè)可以幫助插入動(dòng)態(tài)內(nèi)容的對(duì)象。
contentFromAnonymousTable() instance (none) 對(duì)content通過匿名表格變成一個(gè)Node數(shù)組。

Property Type Kind Description
adjacency String static, parameter 這個(gè)參數(shù)指定相對(duì)于給定元素,內(nèi)容將被放置的位置。 可能的值是: 'beforeBegin', 'afterBegin', 'beforeEnd', 和 'afterEnd'.
element Object instance 與插入物做參照元素對(duì)象。
content String instance 被插入的 HTML 。

The Insertion object

這個(gè)對(duì)象是其他類似功能的根。它沒有任何屬性和方法。在這個(gè)對(duì)象中定義的類仍然可以被視為傳統(tǒng)的抽象類。

The Insertion.Before class

繼承自 Abstract.Insertion

在給定元素開始標(biāo)記的前面插入HTML。

Method Kind Arguments Description
[ctor](element, content) constructor element: element object or id, content: HTML to be inserted 繼承自   Abstract.Insertion. 創(chuàng)建一個(gè)可以幫助插入動(dòng)態(tài)內(nèi)容的對(duì)象。

下面的代碼

<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.Before('person', 'Chief '); </script>

將把 HTML 變?yōu)?/p> <br>Hello, Chief <span id="person" style="color:red;">Wiggum. How's it going?</span>

The Insertion.Top class

繼承自 Abstract.Insertion

在給定元素第一個(gè)子節(jié)點(diǎn)位置插入 HTML。內(nèi)容將位于元素的開始標(biāo)記的緊后面。

Method Kind Arguments Description
[ctor](element, content) constructor element: element object or id, content: HTML to be inserted 繼承自  Abstract.Insertion. 創(chuàng)建一個(gè)可以幫助插入動(dòng)態(tài)內(nèi)容的對(duì)象。

下面的代碼

<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.Top('person', 'Mr. '); </script>

將把 HTML 變?yōu)?/p> <br>Hello, <span id="person" style="color:red;">Mr. Wiggum. How's it going?</span>

The Insertion.Bottom class

Inherits from Abstract.Insertion

在給定元素最后一個(gè)子節(jié)點(diǎn)位置插入 HTML。內(nèi)容將位于元素的結(jié)束標(biāo)記的緊前面。

Method Kind Arguments Description
[ctor](element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.

The following code

<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>
<script> new Insertion.Bottom('person', " What's up?"); </script>

Will change the HTML to

<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going? What's up?</span>

The Insertion.After class

Inherits from Abstract.Insertion

在給定元素結(jié)束標(biāo)記的后面插入HTML。

Method Kind Arguments Description
[ctor](element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.

The following code

<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>
<script> new Insertion.After('person', ' Are you there?'); </script>

Will change the HTML to

<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> Are you there?

The Field object

這個(gè)對(duì)象提供操作表單中的輸入項(xiàng)目的功能性方法。

Method Kind Arguments Description
clear(field1 [, field2 [, field3 [...]]]) instance fieldN: field element object or id 清除傳入表單中項(xiàng)目元素的值。
present(field1 [, field2 [, field3 [...]]]) instance fieldN: field element object or id 只有在所有的表單項(xiàng)目都不為空時(shí)返回 true
focus(field) instance field: field element object or id 移動(dòng)焦點(diǎn)到給定的表單項(xiàng)目。
select(field) instance field: field element object or id 選擇支持項(xiàng)目值選擇的表單項(xiàng)目的值。
activate(field) instance field: field element object or id 移動(dòng)焦點(diǎn)并且選擇支持項(xiàng)目值選擇的表單項(xiàng)目的值。

The Form object

這個(gè)對(duì)象提供操作表單和他們的輸入元素的功能性方法。

Method Kind Arguments Description
serialize(form) instance form: form element object or id 返回url參數(shù)格式的項(xiàng)目名和值的列表, 如'field1=value1&field2=value2&field3=value3'。
findFirstElement(form) instance form: form element object or id 返回Form中第一個(gè)Enable的對(duì)象。
getElements(form) instance form: form element object or id 返回包含所有在表單中輸入項(xiàng)目的 Array 對(duì)象。
getInputs(form [, typeName [, name]]) instance form: form element object or id, typeName: the type of the input element, name: the name of the input element. 返回一個(gè) Array 包含所有在表單中的 <input> 元素。 另外, 這個(gè)列表可以對(duì)元素的類型或名字屬性進(jìn)行過濾。
disable(form) instance form: form element object or id 使表單中的所有輸入項(xiàng)目無效。
enable(form) instance form: form element object or id 使表單中的所有輸入項(xiàng)目有效。
focusFirstElement(form) instance form: form element object or id 激活第一個(gè)表單中可視的,有效的輸入項(xiàng)目。
reset(form) instance form: form element object or id 重置表單。和調(diào)用表單對(duì)象的 reset() 方法一樣。

The Form.Element object

這個(gè)對(duì)象提供表單對(duì)象中的可視和非可視元素的功能性方法。

Method Kind Arguments Description
serialize(element) instance element: element object or id 返回元素的 名稱=值 對(duì), 如 'elementName=elementValue'。
getValue(element) instance element: element object or id 返回元素的值。

The Form.Element.Serializers object

這個(gè)對(duì)象提供了內(nèi)部使用的用來協(xié)助解析出表單元素的當(dāng)前值的一些有用的方法。

Method Kind Arguments Description
inputSelector(element) instance element: object or id of a form element that has the checked property, like a radio button or checkbox. 返回帶有元素名稱和值的 Array , 如 ['elementName', 'elementValue']
textarea(element) instance element: object or id of a form element that has the value property, like a textbox, button or password field. 返回帶有元素名稱和值的 Array , 如 ['elementName', 'elementValue']
select(element) instance element: object of a <select> element 返回帶有元素名稱和所有被選擇的選項(xiàng)的值或文本的 Array , 如 ['elementName', 'selOpt1 selOpt4 selOpt9']

The Abstract.TimedObserver class

這個(gè)類是用于其它監(jiān)聽一個(gè)元素的值(或者任何類中涉及的屬性)變化的類的基類,這個(gè)類像一個(gè)抽象類一樣被使用。

子類可以被創(chuàng)建來監(jiān)聽如輸入項(xiàng)目值,或style屬性,或表格的行數(shù),或者其他任何對(duì)跟蹤變化相關(guān)的東西。

子類必須實(shí)現(xiàn)這個(gè)方法來決定什么才是被監(jiān)聽的元素的當(dāng)前值。
Method Kind Arguments Description
[ctor](element, frequency, callback) constructor element: element object or id, frequency: interval in seconds, callback: function to be called when the element changes 創(chuàng)建一個(gè)監(jiān)聽元素的對(duì)象。
getValue() instance, abstract (none) 子類必須實(shí)現(xiàn)這個(gè)方法以瘊定什么這個(gè)元素被監(jiān)視的當(dāng)前值。
registerCallback() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 被這個(gè)對(duì)象自己調(diào)用來開始監(jiān)聽那個(gè)元素。
onTimerEvent() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 被這個(gè)對(duì)象自己調(diào)用來周期性的檢查那個(gè)元素。

Property Type Description
element Object 被監(jiān)聽的元素對(duì)象。
frequency Number 每次檢查中的以秒為單位的時(shí)間間隔。
callback Function(Object, String) 只要元素改變這個(gè)方法就會(huì)被調(diào)用。 會(huì)接收到元素對(duì)象和新值作為參數(shù)。
lastValue String 元素被核實(shí)的最后一個(gè)值。

The Form.Element.Observer class

繼承自 Abstract.TimedObserver

Abstract.TimedObserver 的一個(gè)實(shí)現(xiàn)類用來監(jiān)聽表單輸入項(xiàng)目的值的變化。當(dāng)你想監(jiān)聽一個(gè)沒有帶報(bào)告值變化事件的元素的時(shí)候使用這個(gè)類。否則的話使用 Form.Element.EventObserver 類代替。

Method Kind Arguments Description
[ctor](element, frequency, callback) constructor element: element object or id, frequency: interval in seconds, callback: function to be called when the element changes 繼承自 Abstract.TimedObserver. 創(chuàng)建一個(gè)監(jiān)聽元素值屬性的對(duì)象。
getValue() instance (none) 返回元素的值。

The Form.Observer class

繼承自 Abstract.TimedObserver

Abstract.TimedObserver 的一個(gè)實(shí)現(xiàn)類用來監(jiān)聽表單中任何數(shù)據(jù)項(xiàng)的值的變化。當(dāng)你想監(jiān)聽一個(gè)沒有帶報(bào)告值變化事件的元素的時(shí)候使用這個(gè)類。 否則的話使用類Form.EventObserver 代替。

Method Kind Arguments Description
[ctor](form, frequency, callback) constructor form: form object or id, frequency: interval in seconds, callback function to be called when any data entry element in the form changes 繼承自 Abstract.TimedObserver. 創(chuàng)建一個(gè)監(jiān)聽表單變化的對(duì)象。
getValue() instance (none) 返回所有表單數(shù)據(jù)的一系列值。

The Abstract.EventObserver class

這個(gè)類被用作其他一些類的基類,這些類具有在一個(gè)元素的值改變事件發(fā)生的時(shí)候執(zhí)行一個(gè)回調(diào)方法這樣的功能。

Abstract.EventObserver 的多個(gè)對(duì)象可以綁定到一個(gè)元素上,不是一個(gè)幫其他的擦出了,而是按照他們付給元素的順序執(zhí)行這些回調(diào)方法。

單選按鈕和復(fù)選框的觸發(fā)事件是 onclick ,而文本框和下拉列表框/下拉列表框的是 onchange 。 

Method Kind Arguments Description
[ctor](element, callback) constructor element: element object or id, callback: function to be called when the event happens 創(chuàng)建監(jiān)聽元素的對(duì)象。
getValue() instance,abstract (none) 子類必須實(shí)現(xiàn)這個(gè)方法以瘊定什么這個(gè)元素被監(jiān)視的當(dāng)前值。
registerCallback() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 被對(duì)象調(diào)用來把自己綁定到元素的事件上。
registerFormCallbacks() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 被對(duì)象調(diào)用來把自己綁定到表單中的每一個(gè)數(shù)據(jù)項(xiàng)元素的事件上。
onElementEvent() instance (none) 這個(gè)方法通常不會(huì)被外部調(diào)用。 將被綁定到元素的事件上。

Property Type Description
element Object 被監(jiān)聽的元素對(duì)象。
callback Function(Object, String) 只要元素改變就調(diào)用的方法。會(huì)接收到元素對(duì)象和新值作為參數(shù)。
lastValue String 元素被核實(shí)的最后一個(gè)值。

The Form.Element.EventObserver class

繼承自 Abstract.EventObserver

Abstract.EventObserver 的一個(gè)實(shí)現(xiàn)類,它在監(jiān)測(cè)到表單中數(shù)據(jù)項(xiàng)元素的值改變的相應(yīng)事件時(shí)候執(zhí)行一個(gè)回調(diào)方法。 如果元素沒有任何報(bào)告變化的事件,那么你可以使用 Form.Element.Observer 類代替。

Method Kind Arguments Description
[ctor](element, callback) constructor element: element object or id, callback: function to be called when the event happens 繼承自 Abstract.EventObserver。 創(chuàng)建一個(gè)監(jiān)聽元素值屬性的對(duì)象。
getValue() instance (none) 返回元素的值。

The Form.EventObserver class

繼承自 Abstract.EventObserver

Abstract.EventObserver 的一個(gè)實(shí)現(xiàn)類,監(jiān)聽表單對(duì)象中包含的任何對(duì)象的任何變化,用元素的事件檢測(cè)值的變化。如果元素沒有任何報(bào)告變化的事件, 那么你可以使用Form.Observer 類代替。
Method Kind Arguments Description
[ctor](form, callback) constructor form: form object or id, callback: function to be called when any data entry element in the form changes 繼承自 Abstract.EventObserver。 創(chuàng)建一個(gè)監(jiān)聽元素值屬性的對(duì)象。
getValue() instance (none) 返回所有表單數(shù)據(jù)的一系列值。

Position 對(duì)象 (預(yù)備文檔)

這個(gè)對(duì)象提供許多和元素位置相關(guān)的方法。

Method Kind Arguments Description
prepare() instance (none) 調(diào)整 deltaXdeltaY 屬性來協(xié)調(diào)在滾動(dòng)位置中的變化。 記得在頁面滾動(dòng)之后的任何調(diào)用的withinIncludingScrolloffset 之前調(diào)用這個(gè)方法。
realOffset(element) instance element: object 返回這個(gè)元素的正確滾動(dòng)偏差的 Array 對(duì)象, 包括所有影響元素的滾動(dòng)偏差。結(jié)果數(shù)組類似 [total_scroll_left, total_scroll_top]
cumulativeOffset(element) instance element: object 回這個(gè)元素的正確滾動(dòng)偏差的 Array 對(duì)象, 包含任何被放置的父元素強(qiáng)加偏差。結(jié)果數(shù)組類似 [total_offset_left, total_offset_top]
within(element, x, y) instance element: object, x and y: coordinates of a point 測(cè)試給定的點(diǎn)的坐標(biāo)是否在給定的元素的外部矩形范圍之內(nèi)。
withinIncludingScrolloffsets(element, x, y) instance element: object, x and y: coordinates of a point  測(cè)試給定的點(diǎn)的坐標(biāo)是否在給定的元素的外部矩形范圍之內(nèi)(包含scroll offsets)。
overlap(mode, element) instance mode: 'vertical' or 'horizontal', element: object 在調(diào)用這個(gè)方法之前需要調(diào)用within() 。這個(gè)方法返回0.0到1.0之間的數(shù)字,來表示坐標(biāo)在元素重疊的分?jǐn)?shù)。 舉個(gè)例子,如果元素是一個(gè)邊長(zhǎng)是100px的正方形的DIV,并且位于(300, 300), 然后 within(divSquare, 330, 330);overlap('vertical', divSquare); 會(huì)返回 0.10,意思是那個(gè)點(diǎn)位于DIV頂部邊框以下 10% (30px) 的位置上。
clone(source, target) instance source: element object or id, target: element object or id 改變目標(biāo)元素的大小尺寸和位置與源元素的相同。