BackboneJS - 从模型中获取集合

时间:2013-12-17 11:26:56

标签: json backbone.js

我有一个基本上看起来像这样的JSON文件:

[
 {
   "First" : [...]
 },

 {
   "Second" : [...]
 },

 {
   "Third" : [...]
 },
]

在我的路由器中我有:

this.totalCollection = new TotalCollection();
this.totalView = new TotalView({el:'#subContent', collection:this.totalCollection});

this.totalCollection.fetch({success: function(collection) {
   self.totalView.collection=collection;
   self.totalView.render();
}});

现在我有我的Backbone模型:

define([
 "jquery",
 "backbone"
],

function($, Backbone) {
var TotalModel = Backbone.Model.extend({
    url: "/TotalCollection.json",

    initialize: function( opts ){
        this.first = new First();
        this.second = new Second();
        this.third = new Third();

        this.on( "change", this.fetchCollections, this );
    },

      fetchCollections: function(){
        this.first.reset( this.get( "First" ) );
        this.second.reset( this.get( "Second" ) );
        this.third.reset( this.get( "Third" ) );
      }
});

return TotalModel;
});

我在我的骨干视图中尝试渲染集合:

render: function() {
    $(this.el).html(this.template(this.collection.toJSON()));
    return this;
}

但我得到错误“首先未定义” - 这是什么问题?

1 个答案:

答案 0 :(得分:1)

您是否确实定义了变量'First','Second'和'Third'?根据你在这里展示的内容,没有任何名称。人们会期望你有几行像......

var First = Backbone.Collection.extend({});
var Second = Backbone.Collection.extend({});
var Third = Backbone.Collection.extend({});

但是你没有提供类似的东西,所以我的第一个假设是你还没有定义它。

根据评论,这可能更符合您的需求:

render: function() {
    $(this.el).html(this.template({collection: this.collection.toJSON())});
    return this;
}

然后..

{{#each collection}}
    {{#each First}}
        /*---*/
    {{/each}}
{{/each}}