我想编写一个小的JavaScript(框架),它可以将函数链接到所有以下函数,这些函数都知道它的前一个数据.
基本上,我并不感兴趣的是膨胀(我认为它很小,对于我更小的项目,尽管它很臃肿)jQuery提供但想模仿它的一些行为 - 主要用于学习目的并且数据可用于所有链接功能.
我喜欢,例如能够做类似的事情:
myJsLib.processForm("user", "pass").url("http://domain.dev/form.php").queryString({ secure: true, errorPage: "login_failure.htm" });
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,所有函数必须在某种程度上了解对方正在做什么.
或者,更具体地说:
myJsLib.getDataIntoArray(jsonObjectOrWhatever).each(function(item) { alert(item); });
Run Code Online (Sandbox Code Playgroud)
其中"item"是getDataIntoArray()创建的数组(并返回?).
我希望我有适当的措辞.我试着用这个例子来说有点过分了.理解jQuery的原型扩展被证明是无用的,但我根本就不熟悉JavaScript.请非常感谢详细(但仍然愚蠢)的解释和代码示例.
非常感谢.
编辑:感谢Andrew,我能够想出一些看起来令人满意的东西.请纠正我似乎有的任何误解,谢谢.
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); });
Run Code Online (Sandbox Code Playgroud)
这似乎按预期工作.有什么警告吗?
这称为流畅的接口,创建它的最佳方法jQuery是从每个函数返回一个主对象(如对象),允许将其他函数调用链接在一起.
这是一个小例子:
function foo() {
this.first = function(first) {
alert(first);
return this;
}
this.second = function(second) {
alert(second);
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
这个通知表明foo该类有两种方法,first并且second.由于这两种方法都返回,this因此可以按照您希望的任何顺序进行链接:
new foo().first("hello").second("world");
new foo().second("hello").first("world");
new foo().first("hello").first("world");
Run Code Online (Sandbox Code Playgroud)
你明白了:)
考虑流畅界面的一个好方法是它们更容易流动并且更容易阅读.上面的示例仅仅是对这种更常规用法的替代:
f = new foo();
f.first("hello");
f.second("world");
Run Code Online (Sandbox Code Playgroud)
这意味着一个流畅的接口并没有规定任何类的实现,除非强制要求您返回,this以便可以链接方法调用.这意味着您可以向此类添加可在任何函数中使用的字段,就像任何其他类一样.