【发布时间】:2015-10-15 17:44:55
【问题描述】:
我正在尝试为 JavaScript 项目创建类似 fluent 的 API。
目前我有这样的事情:
function Foo(a, b) {
this.a = a;
this.b = b;
this.Set = function(attr, val) {
this[attr] = val;
return this;
},
this.refresh = function() {
//do something
}
};
这使我可以编写以下内容:
var foo = new Foo("Hello", "World");
// foo = { a : "Hello", b : "World" }
foo.Set("c", "!");
// foo = { a : "Hello", b : "World", c : "!" }
foo.Set(...);
//...
编写流畅的 API 的好处是菊花链方法调用,因此我可以更轻松、更易读地编写 foo.Set(...).Set(...).Set(...)
编写基本 API 没问题,但我想知道如何检测菊花链中的最后一个 Set 调用,因为在这个调用中我想调用 refresh。
我想这样做是为了避免用户需要手动附加.refresh()。
有没有人处理过这样的事情?
谢谢, erip
编辑
所需的伪代码效果:
function Foo(a, b) {
this.a = a;
this.b = b;
this.Set = function(attr, val) {
this[attr] = val;
//if this Set is the last
// return this.refresh();
return this;
},
this.refresh = function() {
//do something
}
};
【问题讨论】:
-
所以在
foo.Set().Set().Set()中,您希望前两个Set调用返回this,但最后一个返回不同的东西? -
@Oriol 如果可能的话,我希望最后一个
Set是void,基本上。 -
你不能。如果你能找到一些技巧来完成这项工作,那可能是个坏主意!
-
@Evert 好的,我不确定是否有好的方法可以做到这一点。我必须添加文档,告诉用户忘记
.refresh(),风险自负。 -
我能想到的唯一方法是使用超时,您可以在每次调用 Set 方法时清除并重新启动。但是,循环不会等待超时完成。
标签: javascript fluent