什么会导致延迟对象被拒绝?

时间:2012-02-10 00:25:06

标签: jquery backbone.js jquery-deferred

我认为我以错误的方式解决这个问题。这就是我尝试做的而不是使用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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

我不确定domReady延迟的实现,请尝试这种方式:

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的顺序完成

相关问题