Imagine we have a Button element
const ourButton = document.getElementById("#theButton");
And we want a fluent API to change the styles of this button without creating a new object, so chain a function like this:
style(ourButton).property("padding").value("32px");
Is this possible? I can't seem to figure out how to create this behaviour. I tried building a Fluent API "the conventional way" by creating a constructor function like this:
var FStyle = function(node) {
this.node = node;
}
FStyle.prototype.property = function(property) {
this.property = property;
return this;
}
FStyle.prototype.value = function(value) {
this.value = value;
this.node.style[this.property] = this.value;
return this;
}
and using it by constructing a new object:
const ourButtonStyle = new FStyle(ourButton);
ourButtonStyle.property("padding").value("64px");
Which works, once. If I would like to add a new style I have to create a whole new object. Why is this?
TL;DR: For learning purposes I'm trying to chain functions but don't understand it fully enough to understand the above behaviour. Returning this in a normal function to chain other functions to it won't do the job either. In the end I would like to "pipe" the result of a function to an other function.
ourButtonStyle.property("foo").value("bar").property("baz").value("qux")should work just fine. (Aside: stuff likeourButtonStyle.property("foo").property("bar").value("baz")is also possible, but confusing, which shows that this might not be the best API design.)node.style.property = value- which is way more minimalistic) is to practice method chaining and creating Fluent API's. And creating a new object every time you want to change a style isn't really practical IMO.new FStyle(…)multiple times, I'm only saying that you could easily use multiple objects in the chain).