Reputation: 10281
I'm having a problem understanding chaining. I have this code fragment:
groups.appendTo(this.selectedList.add(this.availableList));
Initially, both selectedList
and availableList
are identical, and contain an HTML ul
with a single li
element. groups
is another ul
with 4 li
elements. On completion, both this.selectedList
and this.availableList
have been modified, and contain the new list items.
How does this work, and what exactly is the add
doing here? It doesn't add the contents of the available list to the selected list. I also thought that add
returned a temporary object? And why is this code any better than:
groups.appendTo(this.AvailableList);
groups.appendTo(this.selectedList);
Thanks.
EDIT
The context is:
(function($) {
$.widget("ui.multiselect", {
options: {...},
_func: function() {
... local 'this':
groups.appendTo(this.selectedList.add(this.availableList));
}
});
})(jQuery);
Upvotes: 0
Views: 234
Reputation: 11822
The nice thing about chaining is that you don't have to perform your selections multiple times and therefore gain performance. All jQuery-functions (plugins too) will return the selection (some will return an altered selection though) they performed on so you can just add another method in the chain like:
$('.classIHaveUsedVeryOften').append(foo).hide().addClass('bar');
In case you would write:
$(.classIHaveUsedVeryOften).append(foo);
$(.classIHaveUsedVeryOften).hide();
$(.classIHaveUsedVeryOften).addClass('bar');
jQuery would have to retrieve all of the matching elements three times. In case you have large DOM structures this can take quite some time actually (i.e. don't do this).
Another possibility of dealing with this issue would be putting your selection into a variable beforehand:
var $mySelection = $(.classIHaveUsedVeryOften);
$mySelection.append(foo);
$mySelection.hide();
$mySelection.addClass('bar');
Upvotes: 1