Search code examples
backbone.js

Backbone ReferenceError


I have Backbone view that looks like this:

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
    }));
  }
});

when I try to render it Backbone returns me the following error:

ReferenceError: myCollection is not defined

But when I change render method to this:

  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
    }));
  }

why he can't find this myCollection method?


Solution

  • You forgot the this keyword, and probably also to invoke the method:

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