【问题标题】:Backbone + RequireJS - A Deferred that awaits the creation of another deferred objectBackbone + RequireJS - 等待创建另一个延迟对象的延迟对象
【发布时间】:2012-10-15 02:51:14
【问题描述】:

我在写一个Backbone + RequireJS的项目,遇到如下情况:

模块 A:

Backbone.Mediator.publish('ajax:fetch:in:module:b');

// I need to do something like **$.ajax(options).done()** here

模块 B:

subscriptions: {
    'ajax:fetch:in:module:b': fetch
},

fetch: {
    $.ajax(options);
}

我尝试在模块 B 中的共享命名空间(如 cache.temp = $.ajax(options))下挂钩 $.ajax(options),然后在模块 A 中调用 cache.temp.done(),但它发生在 $.ajax(options) 被创建之前,所以 cache.temp 是只是一个undefined

我想解决这个问题的一种方法是创建一个 deferred,在 $.ajax(options) 准备好之前延迟代码的执行,但我不太确定这是否可行。或者如果周围有更好的想法,我会全力以赴。

【问题讨论】:

  • 您是否在 $.ajax 设置中设置了“完成”回调?
  • 这些请求的顺序是否重要,还是您只需要知道两者何时完成?

标签: javascript jquery backbone.js requirejs jquery-deferred


【解决方案1】:

这是 requirejs 与 jquery deferred 一起使用的简单示例:

moduleA.js

define(['require', 'jquery'], function(require, $) {

    var deferred = $.Deferred();

    require(['moduleB'], function(moduleB) {
        deferred.resolve(moduleB);
    });

    return deferred.promise();

});

app.js

require(['moduleA'], function(deferred) {
    deferred.done(function(moduleA) {
        console.log(moduleA);
    });
});

【讨论】:

    【解决方案2】:

    如果您有 ajax 或延迟 obj,您可以像这样使用 $.when$.then

    $.when( ajax call).then( do other thing)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      相关资源
      最近更新 更多