Mauro
Mauro

Reputation: 4224

Why is Backbone.js looking for the template before I render the view?

I'm new to Backbone.js and I'm writing a small app. I decided to structure everything related to each resource (books, authors) in separate files (books.js, authors.js). Each file features four BBjs classes: a model, a collection, a model view and a collection view corresponding to the given resource. This was working fine when only one of this files was to be included.

Now I'm working on a screen that should show a book collection in a specific author page. I do not intend to render any of the author views, but only to use the author model. However, Backbone is failing with Uncaught TypeError: Cannot read property 'replace' of undefined (underscore.js) because it's looking for a template that's not present on this page.

My author view class looks like this:

app.AuthorView = Backbone.View.extend({
    ...
    template: _.template( $('#book-table-row-template').html() ),
    ...
    render: function(e) { ... }
});

The page does not feature any #book-table-row-template element (I guess that's what triggering the error) but I'm not even instantiating this view. What am I doing wrong? Is there any other more productive way to organize my backbone classes?

Upvotes: 0

Views: 92

Answers (1)

kalley
kalley

Reputation: 18462

You are calling the _.template function right away. It doesn't wait for instantiation. And if there is no #book-table-row-template, jQuery will not find that either.

If you want it to wait until instantiation, set this.template in your initialize method, like so:

initialize: function() {
  this.template = _.template( $('#book-table-row-template').html() );
}

Upvotes: 1

Related Questions