In this post, I want to talk about JavaScript chaining structure, how it works and why we should use it?
What’s the chaining structure?
You may used some JavaScript libraries that has an API like this:
booJs().setOption("first", 1).goTo(2).start();
those plugins or modules, follow a principle that called JavaScript chaining method, so you can call methods after each other, just like a chain.
For giving a broad picture of this structure, see this code, this is the non-chaining method of the previous code:
var booInstance = booJs();
booInstance.setOption("first", 1);
booInstance.goTo(2);
booInstance.start();
As you can see, with chaining methods we have smaller code size and more human readable source code, isn’t that better?
How it works?
So now I want to show how it works actually, it’s quite simple. See this piece of code:
var booJs = function() {
var _setOption = function(key, value) {
console.log("Set " + key + " to " + value);
};
var _goTo = function(step) {
console.log("Go to step " + step);
};
var _start = function() {
console.log("Whohooo, engine started!");
};
//Public API
return {
setOption: _setOption,
goTo: _goTo,
start: _start
};
};
This is a simple code, with some private methods and a public API. Suppose we want to do these three steps:
- Set option first to the 1 with setOption method
- Going to step 2 with goTo method.
- Then start the engine with start method.
So we should do:
var booInstance = booJs();
booInstance.setOption("first", 1);
booInstance.goTo(2);
booInstance.start();
And we will get this result:
Set first to 1
Go to step 2
Whohooo, engine started!
Let’s re-write that simple library with chaining structure, all we need to do is return the current instance of booJs in each methods, so final library will we something like this:
var booJs = function() {
var _setOption = function(key, value) {
console.log("Set " + key + " to " + value);
return this; //return current instance of booJs here
};
var _goTo = function(step) {
console.log("Go to step " + step);
return this; //return current instance of booJs here
};
var _start = function() {
console.log("Whohooo, engine started!");
return this; //return current instance of booJs here
};
//Public API
return {
setOption: _setOption,
goTo: _goTo,
start: _start
};
};
And now we can use the API this way:
booJs().setOption("first", 1).goTo(2).start()
result also will be the same of non-chaining structure.
Conclusion
By using chaining method in JavaScript, we will have simple API and more human readable code, but I personally don’t prefer long chains in methods.
All we need to do for creating chaining methods is to return the current instance of library in each methods, so after calling every methods of library we have the created instance of the library and all other methods are available and can be called after calling methods.