0

im trying to set an element with a class of either 'inactive' or 'active' depending on the models isActive property.

<tr class="inactive">

And heres what I have. 'inactive' is default. the resulting render is that all tr elements have class of 'inactive'

var ItemView = Backbone.View.extend({

   tagName: "tr",
   className: 'inactive',


   render : function() {
       this.className = this.model.get('Active') ? 'active' : 'inactive';

       ...


       this.$el.html( this.template(data) );
   }

});

Found some small print

  className: function() {
     var el = this.model.get('Active') ? 'active' : 'inactive';   // Set active flag in class
     return el;
  },

However, now get error: 'this.model' is undefined suggesting that className function is run prior to initialize. im using default initializer. and this.model in render never had a problem.

Gabe Rainbow
  • 3,658
  • 4
  • 32
  • 42
  • AHA. Small print in documentation: Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime. – Gabe Rainbow Sep 28 '13 at 18:24
  • How are you instantiating the view? `this.model` should be available: http://jsfiddle.net/ambiguous/Su9dn/ – mu is too short Sep 28 '13 at 19:19

2 Answers2

0

If you're going to be checking whether or not the model is active or not, why do you bother having a default className? It seems to me that you'd skip the default if you're setting it while rendering the function. Also, it might be easier to just add the className into your template:

template: _.template('<tr class="<% active ? 'active' : 'inactive' %>">...</tr>');

Then, you don't need to worry about anywhere else it might change and you have less code.

EDIT:

Here's a link that provides another way of dynamically listening for the attribute change and updating your view:

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

Community
  • 1
  • 1
EmptyArsenal
  • 7,314
  • 4
  • 33
  • 56
  • your point is put it into the template. and have done that previously but want to abstract that out. there are several views like that. – Gabe Rainbow Sep 28 '13 at 19:07
  • Meaning, there's no point in setting the className at the beginning of your view object if you're just going to reset it again later. – EmptyArsenal Sep 28 '13 at 19:07
0

I added the runtime classname using jquery addClass.

  render: function() {

     var isactive = this.model.get("Active") ? "" : "inactive";
     this.$el.removeClass('inactive').addClass(isactive);


  }
Gabe Rainbow
  • 3,658
  • 4
  • 32
  • 42