【问题标题】:What would cause a deferred object to be rejected?什么会导致延迟对象被拒绝?
【发布时间】:2012-02-10 00:25:05
【问题描述】:

我认为我的做法是错误的。这就是我想要做的,而不是使用 RequireJS 或 LABjs:

var APP = {};
APP._timers = {};
APP._timelines = {};

$.when(
    $.getScript('/app/models/Timer.js'),
    $.getScript('/app/models/Section.js'),

    $.getScript('/app/collections/Timers.js'),
    $.getScript('/app/collections/Sections.js'),

    $.getScript('/app/views/SectionView.js'),
    $.getScript('/app/views/APPView.js'),

    $.Deferred(function(deferred){
        $(deferred.resolve);
    })
).done(function () {
    alert('done');
    console.log(APP.APPView);
    var foo = new APP.APPView;
    APP._timelines.main = new APP.Timers('main');
    APP._timelines.branched = new APP.Timers('branched');
}).fail(function(){
    alert('failed');
});

它正在警告failed,没有任何内容写入控制台。

如果我打开这些文件中的任何一个,比如APPView.js 并在文件的顶部或底部发出警告,我就会看到它出现。这是该文件的示例:

APP.APPView = Backbone.View.extend({
    el : $("#app-view"),
    initialize : function () {
        alert('App view initialized'); // Never gets called
        this.sectionVew = new APP.SectionView();
    }
});
alert('Inside APPView.js'); // gets called

【问题讨论】:

  • 在您的alert('fail'); 之后输入如下内容:console.log(arguments),您可能会发现它正在返回有关问题的详细信息?
  • 为什么要创建一个可以立即自行解决的 Deferred?
  • @JohnFlatness 当 DOMReady 事件发生或已经发生时立即解决。
  • @KevinB 啊,我明白了,我跳过了那里的$()

标签: jquery backbone.js jquery-deferred


【解决方案1】:

我认为失败的原因是您尝试在 $.when 中加载所有脚本而不管理依赖项。每个$.getScript 都是异步的,它们不需要按顺序完成。因此,如果您的视图在模型执行之前加载,它将尝试使用未定义的模型时停止。 简而言之,要做到这一点,您必须:

  1. 手动管理依赖关系。即一旦加载模型,然后加载视图。
  2. 编写真正独立的模块
  3. 这是最简单的,停止尝试手动执行所有这些操作并使用 AMD 加载程序,例如 require.js。这就是它存在的原因!

【讨论】:

  • 你说得对,我的一个依赖项没有及时加载。我必须感谢上面 cmets 的 James Khoury,他告诉我 console.log(arguments) 指出了我未定义的函数错误。谢谢!
【解决方案2】:

我不确定你的 domReady deferred 的实现,这样试试:

var APP = {};
APP._timers = {};
APP._timelines = {};

var domRdyDeferred = $.Deferred();
$(domRdyDeferred.resolve);

$.when(
    $.getScript('/app/models/Timer.js'),
    $.getScript('/app/models/Section.js'),

    $.getScript('/app/collections/Timers.js'),
    $.getScript('/app/collections/Sections.js'),

    $.getScript('/app/views/SectionView.js'),
    $.getScript('/app/views/APPView.js'),

    domRdyDeferred
).done(function () {
    alert('done');
    console.log(APP.APPView);
    var foo = new APP.APPView;
    APP._timelines.main = new APP.Timers('main');
    APP._timelines.branched = new APP.Timers('branched');
}).fail(function(){
    console.log(arguments);
    alert('failed');
});

请务必注意,尽管它们可能不会按照您将它们添加到 $.when 的顺序完成

【讨论】:

猜你喜欢
  • 2021-07-30
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 2015-10-02
  • 1970-01-01
相关资源
最近更新 更多