【发布时间】:2011-09-15 05:46:37
【问题描述】:
也许我的问题本身就偏离了简单性: 鉴于我.trigger() 发生了一个事件,我如何确保.trigger() 后面的代码在 之前不会执行整个事件处理函数已经完成,包括其中的所有动画、延迟等?
我希望我在这里遗漏了一些东西;我正在设置一个带有一堆自定义事件的 UI。一些事件实际上只是其他事件的聚合;例如:
// ...
'cb-ui.hide': function(event){
// do stuff to hide
},
'cb-ui.close': function(event){
$(this).trigger('cb-ui.hide');
// more stuff for close
},
// ...
鉴于cb-ui.hide 事件中有一个动画,例如.fadeOut(1500),看来(在我的测试中)剩余的// more stuff for close 不会等待动画完成触发的事件。我在想(在引用文档之前).trigger() 可能会有一个可选的回调参数,就像动画方法一样:
$(this).trigger('cb-ui.hide', function(event){
// more stuff for close
});
但情况似乎并非如此。由于事件触发器没有阻塞(或似乎至少没有),我可以做些什么来强制实现所需的功能,同时保持我一直在构建的事件处理程序/触发器实现关了吗?
更具体地说:
$('[data-cb-ui-class="window"]').live({
'cb-ui.hide': function(event){
$(this).find('[data-cb-ui-class="content"]').animate({
opacity: 0
}, 1000);
},
'cb-ui.show': function(event){
$(this).find('[data-cb-ui-class="content"]').animate({
opacity: 1
}, 1000);
}
'cb-ui.close': function(event){
$(this).trigger('cb-ui.hide');
$(this).find('[data-cb-ui-class="content"]').animate({
height: 'hide' // happening simultaneously to the animation of 'cb-ui.hide'
// expected to happen in tandem; one after the other
}, 1000);
},
'cb-ui.update': function(event, html){
// none of this is working as expected; the expected being, the 'cb-ui.hide'
// event is triggered (thus fading the [...-content] out) the HTML content is
// updated, then the [...-content] is faded back in from 'cb-ui.show'
// instead its just a mess that results in it fading out
$(this).trigger('cb-ui.hide');
$(this).find('[data-cb-ui-class="content"]').html(html);
$(this).trigger('cb-ui-show');
}
});
$('#foo').trigger('cb-ui.update', ['<p>Hello world!</p>']); // #foo is bound
这个示例动画大约需要 2 秒,但似乎需要 1 秒;两个动画彼此同时发生,而不是按逻辑顺序发生。
【问题讨论】:
标签: event-handling callback jquery-animate jquery