我想編寫一個小型的JavaScript(框架),可以鏈接功能與所有以下功能知道其前任的數據。什麼是最簡單的方式來實現像jQuery這樣的可鏈接的JavaScript框架?
基本上,我對jQuery提供的膨脹(我意識到它很小,對於我的更小的項目雖然膨脹)並不感興趣,但是想要模仿它的一些行爲 - 主要用於學習目的和數據可用於所有鏈接功能。
我很樂意,例如能夠做這樣的事情:
myJsLib.processForm("user", "pass").url("http://domain.dev/form.php").queryString({ secure: true, errorPage: "login_failure.htm" });
在上面的例子中的所有功能,必須意識到在一定程度上什麼其他正在做。
,或者更具體:
myJsLib.getDataIntoArray(jsonObjectOrWhatever).each(function(item) { alert(item); });
其中, 「項目」 將是數組getDataIntoArray()創建(返回?)。
我希望我有這個適當的措辭。我試圖讓這個例子太過分了。理解jQuery的原型擴展已被證明是無用的,但我並不熟悉JavaScript。我非常感謝一個詳細的(但愚蠢的)解釋和代碼示例,請。
非常感謝。
編輯:感謝安德魯我能夠拿出一些似乎令人滿意的東西。請糾正我似乎有任何誤解,謝謝。
function myLib()
{
this.properties = ['status', 'window', 'ui'],
this.inputArrayParms = function(parms)
{
for (var i = 0, len = parms.length; i < len; i++)
{
this.properties[this.properties.length] = parms[i];
}
return this;
},
this.each = function(callback)
{
for (var i = 0, len = this.properties.length; i < len; i++)
{
callback(this.properties[i]);
}
return this;
}
}
var f = new myLib;
f.inputArrayParms(["one", "two", "three"]).each(function(theMsg){ alert(theMsg); });
這似乎按預期工作。任何警告?
@Brainsick:不需要在標題中添加「已解決」。另外,如果安德魯的答案幫助你解決了你的問題,作爲禮貌,你應該點擊旁邊的複選標記標記他的答案爲可接受的。 – 2009-09-16 04:41:19
Gotcha。非常抱歉! – Brainsick 2009-09-16 05:23:39
您可以用下面的代碼替換執行this.properties [this.properties.length] = parms [i]的for循環:Array.prototype.push.apply(this.properties,parms); – 2009-09-16 05:27:15