I'm trying to create a fluent-like API for a JavaScript project.
Currently I have something like this:
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
}
};
This allows me to write the following:
var foo = new Foo("Hello", "World");
// foo = { a : "Hello", b : "World" }
foo.Set("c", "!");
// foo = { a : "Hello", b : "World", c : "!" }
foo.Set(...);
//...
The benefit of writing a fluent API is to daisy-chain method calls, so I could more easily and readably write foo.Set(...).Set(...).Set(...)
Writing the basic API is fine, but I want to know how to detect the last Set
call in the daisy-chain, because in this call I'd like to call refresh
.
I'd like to do this to avoid the user from needing to manually append a .refresh()
.
Has anyone dealt with something like this?
Thanks, erip
EDIT
Desired effect in pseudocode:
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
}
};