When developing a plugin we are recommended to maintain the chainability. Using the this keyword maintains the chainability.
So, what is the chaining called in jquery?
Proper demonstration (or description) would be greatly appreciated. Thanks.
When developing a plugin we are recommended to maintain the chainability. Using the this keyword maintains the chainability.
So, what is the chaining called in jquery?
Proper demonstration (or description) would be greatly appreciated. Thanks.
It's called chaining in jQuery.
Plugins should return this
so that another jQuery method can be called on the same object when the plugin is done.
Example from the jQuery docs (http://learn.jquery.com/plugins/basic-plugin-creation/#chaining):
// Return this in my plugin
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
}
// So I can chain another jQuery method
$( "a" ).greenify().addClass( "greenified" );
That article is using "chaining" as shorthand for "method chaining." Method chaining is a style of coding that often used in javascript, including in the jquery library.
Here is the basic jist.
Javascript methods can return references to javascript objects. So if you call a method on an object and it returns a reference to an object -- and then you call a method on the (returned) object, then you have a "method chain."
In coding terms, method chains look like this:
d3.select("body")
.append("p")
.text("New paragraph!");
In this case, the select method is called on the d3 object. That select method returns a reference to the body element in the dom (as represented in the d3 library). Then append is called on the body element. Append returns a reference to the p element. Text is called on this p element. The select, append and text methods are said to be "chained" because they are written all together on one line.
I learned about method chaining from this great post, which is where the examples in my answer come from.
$('#id')
.css('color', 'red')
.wrap('<div/>')
.appendTo(another);
When you can chain method calls this way because each method returns object itself - this is called, well, chaining.