6

I've a Backbone view where the className is set dynamically with a function:

app.Views.ItemRequestView = Backbone.View.extend({

    tagName     : 'tr',

    className   : function(){

        var classRow = '';

        if(this.model.getState() == app.Models.Request.status.wait.key) {
            classRow = app.Models.Request.status.wait.color + ' bolder';
        }
        else if(this.model.getState() == app.Models.Request.status.confirm.key){
            classRow = app.Models.Request.status.confirm.color + ' bolder';
        }

        return classRow;
    },

When I update the model of the view I trigger a change event who render the view. The problem is that the className is not recalculate with the render... How can I recalculate the className when I render the view ?

Anyone have an idea ? Thanks

user2568596
  • 63
  • 1
  • 3

1 Answers1

8

You will have to update your class manually after the render method. Backbone initializes the className of the element of your View only once time during the _ensureElement method:

_ensureElement: function() {
      if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
        this.setElement($el, false);
      } else {
        this.setElement(_.result(this, 'el'), false);
      }
}

If you take a look it has a check in case of the element already exists. Anyway, you can do that manually in your render method:

render: function(){
   //Your logic
   this.$el.attr('class', _.result(this, 'className'));
}
Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
  • 4
    overkill alert, all you need to do is `this.$el.addClass('classname')` before the view is displayed. – Josh Bedo Jul 10 '14 at 17:06
  • 1
    Unless you're doing something more complicated than adding a class (adding some, toggling some, etc). For that reason it's not overkill, it's robust. – Nick Manning Nov 12 '16 at 13:41