Question

Sorry, but apparently I don't understand chaining enough to figure out this problem...

I'm implementing a jQuery carousel plugin (jCarouselLite) and I'm trying to add an option to 'remove' one of the carousel items (currently <div class="remove">)...

initEvents: function() {
        var self = this;
        // Bind jQuery event for REMOVE button click
        $('.remove').live('click', function() {     
            // Need to save the ID that we're removing
            var item = $(this).closest('li.sort');
            var itemId = item.attr("id");

            $(this).removeItem();

            self.refreshDisplay(itemId);
        }); 


 $.fn.removeItem = (function() {
  var item = this.closest('li.sort'); // could save this call by passing param

  item.fadeOut("normal", function() {
         $(this).remove();
      });

   // preserve jQuery chain
   return this;
 });
},

refreshDisplay(itemId) {
  // ...
  // redraws carousel
  // ...
  // itemId is used to remove from the array of Items to show (class-wide scope)
}

Since there's no clean way to 'refresh' the jCarouselLite plugin (maybe something I'll try implementing in the actual plugin later) the quick and dirty fix for this is to just regenerate the Carousel.

The issue is I'm trying to fade out the element clicked, however, it seems like the refreshDisplay() is called before the animation of fading out (and removing) the clicked item is completed. I've verified this by commenting out the self.refreshDisplay(itemId); line and it fades out and removes as expected.

So I guess there's a certain way I need to chain this? I've done a couple hours of reading on how chaining works and I thought I understood it, but apparently not.

Any and all help is appreciated, thanks!

Was it helpful?

Solution

The purpose of chaining is to allow multiple commands to share a base object, but it doesn't cause each command to wait for the previous one.

For that, you need to use a callback. Something like

initEvents: function() {
        var self = this;
        // Bind jQuery event for REMOVE button click
        $('.remove').live('click', function() {     
            // Need to save the ID that we're removing
            var item = $(this).closest('li.sort');
            var itemId = item.attr("id");

            $(this).removeItem(function() {
                self.refreshDisplay(itemId);
            });
        }); 


 $.fn.removeItem = (function(callback) {
  var item = this.closest('li.sort'); // could save this call by passing param

  item.fadeOut("normal", function() {
         $(this).remove();
         callback();  //now your refresh is being called after the fade.
      });

   // preserve jQuery chain
   return this;
 });
},
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top