不能将“toJSON”与backbone.js关系模型的子模型(使用get方法)一起使用

时间:2014-01-13 10:54:49

标签: backbone.js

我是backbone.js的新手,并努力寻找足够的材料来教育自己。我当前的问题与使用下划线将Backbone关系模型呈现到模板有关。我的主干关系模型如下所示:

var stateReportBillModel = Backbone.RelationalModel.extend({
        urlRoot: 'rest/stateReportingBill',
        defaults:{
          relations: [
            {
                type: Backbone.HasMany,
                key: 'errors',
                relatedModel: 'errorModel',
                collectionType: 'errorCollection',
                includeInJSON: false,
                autoFetch: true
            },
            {
                type: Backbone.HasOne,
                key: 'claimInformation',
                relatedModel: 'claimInformationModel',
                includeInJSON: false,
                autoFetch: true
            },
            {
                type: Backbone.HasOne,
                key: 'billInformation',
                relatedModel: 'billInformationModel',
                includeInJSON: false,
                autoFetch:true
            },
            {
                type: Backbone.HasMany,
                key: 'lineItems',
                relatedModel: 'lineItemModel',
                collectionType: 'lineItemCollection',
                includeInJSON: false,
                autoFetch: true
            },
            {
                type: Backbone.HasOne,
                key: 'trackingInformation',
                relatedModel: 'trackingInformationModel',
                includeInJSON: false,
                autoFetch: true
            },
          ]
        },
        initialize: function(properties) {
            console.log('New StateReportingBill created');
        }
    });

  return stateReportBillModel;

});

调用成功的RESTful get函数后,我尝试使用模板在视图中呈现模型。使用常规模型,我可以按照以下方式将模型传递给模板:

this.$el.append(this.errorsTemplate({
            errors: errors.toJSON(),
            errorTemplate: this.errorTemplate
      }));

但是在从上述模型中检索错误后,如果我尝试以这种方式传递错误模型,我会收到以下错误:

Uncaught TypeError: Object #<Object> has no method 'toJSON'

这就是我想要做的事情

var errorsModel = this.model.get("errors");
this.$el.append(this.errorsTemplate({
   errors: errorsModel.toJSON(),
   errorTemplate: this.errorTemplate
}));

我的errorsTemplate和errorTemplate如下所示:

<tbody>
<% _.each(errors, function(error) { %>
<%= errorTemplate(error) %>
<% }); %>
</tbody>
<tr>
    <td><%= message %></td>
    <td><%= type %></td>
    <td><%= value %></td>
    <td><%= formElement %></td>
    <td><%= lineNo %></td>
    <td><%= compoundSeqNumber %></td>
</tr>

我假设在从关系模型获取子模型后我不能像常规模型一样使用toJSON。另一方面,如果我在整个关系模型上调用JSON,它允许我这样做。如果是这种情况,我该如何将模型传递给模板。我不想一次将整个关系模型传递给一个大模板而是一次获得一个子模型并将它们传递给不同的小模板。任何形式的帮助将非常感激。感谢。

0 个答案:

没有答案