Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 457
Jakub Arnold Avatar asked Mar 31 '12 12:03

Jakub Arnold


People also ask

What is backbone JS model?

Model contains dynamic data and its logic. It performs various types of action on the data like validation, conversion, computed properties, access control etc. 1. It extends Backbone.

What is the only method available in the backbone JS history?

There is only method named "start" can be used to manipulate the Backbone. js history.

What is backbone JS give its features?

Backbone. js allows developers to develop one page applications and front-end much easier and better using JavaScript functions. Backbone provides different types of building blocks like models, views, events, routers and collections for assembling client side web applications.


3 Answers

You should use the attributes hash/function:

attributes: function () {
 //GET CLASS NAME FROM MODEL
 return { 'class' : this.getClass() }
},
getClass: function() {
   return this.model.get('classname')
}
like image 84
mgm8870 Avatar answered Sep 23 '22 09:09

mgm8870


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
  }
like image 23
Trevor Avatar answered Sep 22 '22 09:09

Trevor


It would be much easier I think to use this.$el.toggleClass or simply add the class inside render.

However if you want to set the class when constructing the view, you can pass it as an option:

view = new App.CommentView({
  model: model,
  className: model.get('parent_id') ? 'comment comment-reply' : 'comment'
})
like image 42
ggozad Avatar answered Sep 22 '22 09:09

ggozad