Backbone / Javascript检查:无法从集合中获取模型

时间:2011-12-20 07:54:54

标签: backbone.js coffeescript

刚刚开始使用骨干和我对如何从集合中检索模型感到困惑。为了给出解释,我有以下路由器方法:

index: (date) ->
  @days = new Demomanager.Collections.DaysCollection(@options)
  @days.reset @options.days
  @days.fetch()
  @view = new Demomanager.Views.Days.IndexView(days: @days)
  $("#calendar").html(@view.render().el)

传递给以下视图:

class Demomanager.Views.Days.IndexView extends Backbone.View
  template: JST["backbone/templates/days/index"]

  initialize: (options) ->
    _.bindAll(this, 'addOne', 'addAll', 'render')
    @options.days.bind('reset', @addAll)
    console.log @options.days

当我在Chrome检查器中检查视图中的最后一行(@ options.days)时,它会返回DaysCollection,其中包含一个包含36个条目的“模型”数组(这是预期的)。

然而,当我改变

console.log @options.days

console.log @options.days.models

我得到一个空数组,而不是36个模型的数组。

最后,如果我通过控制台本身(window.router.days.models)访问同一个对象,它会按预期显示36个模型。

因此,简而言之:发生了什么,以及如何从视图中访问这些模型?

非常感谢......

2 个答案:

答案 0 :(得分:2)

也许是因为你进行异步调用。因此,当您在视图的构造函数中记录options.days时,数据尚未加载。最好在days.fetch的成功回调中创建您的视图。这样做也可以在加载失败时启动另一个视图。

答案 1 :(得分:1)

您想将获取移动到视图中:

var IndexView = Backbone.View.extend({
    collection: new Demomanager.Collections.DaysCollection(options),
    template: myTemplate,

    initialize: function() {
        $("#calendar").html(_.template(myTemplate, {}));

        this.collection.fetch();
        this.collection.reset(null, options.days); // don't know how coffeescript works, but first arg here is models set not the options object

        this.collection.bind("add", this.addOne, this);
    },


    addAll: function() {
        this.collection.each(this.addOne, this);
    },
    addOne: function(model) {
        $(this.el).append(new ChildView({model: model}));
    }

});
相关问题