jQuery“准备好”的事件可能吗?

时间:2012-02-07 07:58:02

标签: javascript jquery

我想做这样的事情:

$("#container").otherBind("foo-content-loaded", function() {alert("immediate or later!");});

“foo-content-loaded”是一个自定义事件,我只会发射一次。 otherBind$.ready()类似,因此如果事件已被触发,处理程序会立即触发,或者它就像常规事件一样。

如何定义otherBind()?很明显,这种绑定的酷CS名称是什么?

1 个答案:

答案 0 :(得分:3)

使用Deferred

,而不是触发自定义事件
var deferred = $.Deferred();

// when content loaded, resolve the Deferred:
deferred.resolve();

在其他地方,您可以添加任意数量的done()处理程序,即使您在事后添加它们也可以调用它们:

deferred.promise().done(function () {
    // content was loaded at some point
});

如果您是通过$.ajax加载内容,则应注意$.ajax个调用已经返回一个Promise接口(Deferreds的受限制接口),您可以将done()个处理程序附加到该接口上

相关问题