Backbone ReferenceError

时间:2016-01-22 09:53:11

标签: backbone.js

我的Backbone视图看起来像这样:

App.Views.HistoricalDataSelector = Backbone.View.extend({
  initialize: function (options) {
    this.template = JST['backbone/templates/historical_data_selector'];
    this.collection = options.collection;
    this.model = options.model;
    this.render();
  },

  myCollection: function() {
    return this.collection.byReportType(this.model.get('report_type')).byReportOrganizationType(this.model.get('report_organization_type'))
  },

  render: function () {
    this.$el.html(this.template({
      collection: myCollection,
      model: this.model
    }));
  }
});

当我尝试渲染它时Backbone返回以下错误:

ReferenceError: myCollection is not defined

但是当我将渲染方法更改为:

  render: function () {
    this.$el.html(this.template({
      collection: this.collection.byReportType(this.model.get('report_type')).byReportOrganizationType(this.model.get('report_organization_type')),
      model: this.model
    }));
  }

为什么他找不到这个myCollection方法?

1 个答案:

答案 0 :(得分:6)

您忘记了this关键字,也可能还要调用方法:

render: function () {
 this.$el.html(this.template({
  collection: this.myCollection(),
  //-----------^ view reference ^---- function invocation ------
  model: this.model
 }));
}