4

抱歉,但显然我对链接的理解不足以解决这个问题......

我正在实现一个 jQuery 轮播插件(jCarouselLite),我正在尝试添加一个选项来“删除”其中一个轮播项目(目前<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)
}

由于没有干净的方法来“刷新” jCarouselLite 插件(也许我稍后会尝试在实际插件中实现),因此快速而肮脏的解决方法就是重新生成 Carousel。

问题是我试图淡出单击的元素,但是,似乎在淡出(并删除)单击的项目的动画完成之前调用了 refreshDisplay() 。我已经通过注释掉该self.refreshDisplay(itemId);行来验证这一点,它会按预期淡出并删除。

所以我想我需要某种方式来链接它?我已经阅读了几个小时关于链接如何工作的内容,并且我认为我理解它,但显然不是。

任何和所有的帮助表示赞赏,谢谢!

4

1 回答 1

3

链接的目的是允许多个命令共享一个基础对象,但它不会导致每个命令都等待前一个命令。

为此,您需要使用回调。就像是

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;
 });
},
于 2010-12-03T19:43:21.443 回答