0

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);
1
  • No - it's copied verbatim from the source (a multiselect plugin), which I've traced through on Firebug to get the results above. Commented Mar 20, 2012 at 12:54

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.