Backbone.js - Where to define view helpers?

12,752

There are a few different places that I put view helpers with Backbone.js:

If the helper is specific to a certain view, put it right in the view definition:

var MyView = Backbone.View.extend({
  tagName: 'div',

  events: {
    ...
  },

  initialize: function() { ... },

  helperOne: function() {
    // Helper code
  },

  anotherHelper: function() {
    // Helper code
  },

  render: function() { 
    ... this.helperOne() ...
  }
});

If the helper will be used by all views, extend the Backbone View class so that all views inherit this function:

_.extend(Backbone.View.prototype, {
  helper: function() {
    // Helper code
  }
}

If you need more complicated sharing of helpers between views, have views extend each other:

var MyOtherView = MyView.extend({

  // ...

  render: function() { 
    ... this.helperOne() ...
  }
});

I'm not sure what is best practice (or if there is an established best practice), but these patterns seem fairly clean and work well.

Share:
12,752
aaronrussell
Author by

aaronrussell

Updated on June 16, 2022

Comments

  • aaronrussell
    aaronrussell almost 2 years

    I've been kicking the tyres of Backbone.js and having a play around in recent weeks, so a bit of a noob question...

    What is the 'correct' way to define and use view helpers in backbone.js?

    As far as I can work out, the only real place to define helpers to use in your templates is on the model or collection itself. However, when that helper is directly returning HTML, this begins to feel a little dirty.

    Is there a better way?