2010-12-03 54 views
4

对不起,但显然我不明白链足够弄清楚这个问题...jQuery的似乎是运行多个电话同时

我采取一个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插件(也许东西,我会尝试在实际执行插件)稍后的快速和肮脏的修复只是重新生成旋转木马。

问题是我试图淡出被单击的元素,但是,看起来refreshDisplay()在淡出(和删除)被单击项目的动画完成之前调用。我已通过评论self.refreshDisplay(itemId);一行来验证此问题,并按预期淡出并删除。

所以我想有一种方法我需要链接?我已经花了几个小时的时间阅读链接是如何工作的,我认为我理解了它,但显然不是。

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

回答

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; 
}); 
}, 
+1

击败我吧! +1,Jacob是完全正确的;-) 另外值得注意的是,它不是同时调用东西的“jQuery”,它的JavaScript一般。请记住,衰落是一种动画,我相信,动画的处理使用超时(等待一小段时间,然后继续动画)。虽然超时正在进行,但您的JavaScript引擎会很乐意继续执行您编写的任何其他命令。 jQuery团队知道这一点,这就是为什么他们的大部分动画函数都带有可选的回调函数。 – Pandincus 2010-12-03 19:45:11