Search code examples
javascriptbackbone.js

backbone js rigth initialization process


This javascript present on all site pages.

    var CategoriesView = Backbone.View.extend({
    el: $('.js-categories-view'),

    initialize: function () {
...
    }

...
    templates: {
      'category-template': _.template($('#js-category-template').html())
    },


  });

And if page haven't element $('.js-categories-view'), code like: new CategoriesView(); it will not be called and initialize not be called too.

But what about templates section?

_.template($('#js-category-template').html()) always called and I get the error:

Uncaught TypeError: Cannot read property 'length' of undefined

Because $('#js-category-template') doesn't present on page and and I don't want store template html on page where this View not needed?


Solution

  • You can check if the needed element present on the current page like this:

    if( $('.js-categories-view').length ){
        new CategoriesView();
    }
    

    And if you want to prevent error when calling the _.template() function, you also need to move the definition of the templates object into the initialize method of the view like follows:

    var CategoriesView = Backbone.View.extend({
      el: $('.js-categories-view'),
    
      initialize: function () {
        this.templates = {
          'category-template': _.template($('#js-category-template').html())
        };
        ...
      }
    });