在我的 jQuery 插件中,我经常希望用户定义一些回调,如下面的简单示例所示
(function($) {
$.fn.myplugin = function(options) {
var s = $.extend({}, options),
$this = $(this);
if (typeof s['initCallback'] === 'function') {
s['initCallback']($this);
}
$this.animate({width: '+=300'}, 3000); /* animation in plugin */
}
})(jQuery);
有时定义的回调包含这样的同步代码,并且此代码按我的预期工作
$('#mydiv').myplugin({
initCallback : function(mydiv) {
$('<div>This is synchronous, so it will entirely executed before animation</div>')
.insertBefore(mydiv);
}
});
但在其他情况下,回调可以定义这样的异步动画
$('#mydiv').myplugin({
initCallback : function(mydiv) {
$('<div>animations are not synchronous here</div>')
.insertBefore(mydiv)
.hide()
.fadeIn(4000); /* animation in callback */
}
});
在最后一种情况下,我们有两个明显重叠的动画,因为在执行完我的剩余插件代码后,回调initCallback()
中没有正确执行。fadeIn()
所以我要问:是否存在一种通用的 jQuery 模式来处理这两种代码(异步/同步)以确保initCallback()
无论它定义了哪个代码,都会终止执行?还是我需要以两种不同的方式对这两种情况进行编码?
此示例的代码可在http://jsfiddle.net/fcalderan/LKttT/上获得
提前致谢。