How can I dynamically set a className for a Backbone.js view based on it's model attributes?

Jakub Arnold picture Jakub Arnold · Mar 31, 2012 · Viewed 8.4k times · Source

Basically what I need is to do something like this

App.CommentView = Backbone.View.extend({
  className: function() {
    if (this.model.get('parent_id')) {
      return 'comment comment-reply';
    } else {
     return 'comment';
    }
  },

The problem is, that at the function passed to className is executed in context of the html of the view template, so I can't call this.model.

Is there any way I can access the model at this point in the rendering process? Or do I need to set the class later, for example in the render function?

Answer

Trevor picture Trevor · Mar 31, 2012

This sounds like a job for model binding.

App.CommentView = Backbone.View.extend({
  initialize: function () {
      // anytime the model's name attribute changes
      this.listenTo(this.model, 'change:name', function (name) {
          if (name === 'hi') {
             this.$el.addClass('hi');
          } else if......
      });
  },
  render: function () {
       // do initial dynamic class set here
  }