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

4

10

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?

Staffordshire answered 31/3, 2012 at 12:53 Comment(0)
G
14

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
  }
Gulick answered 31/3, 2012 at 14:58 Comment(0)
A
3

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')
}
Agra answered 7/11, 2012 at 21:29 Comment(1)
Nope, that is not true. That "attributes" function is exectued at _ensureElement() method, and at that point you do not have access to this.modelBlintze
P
2

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'
})
Psychopharmacology answered 31/3, 2012 at 14:28 Comment(0)
H
0

I did it at View initialize

App.CommentView = Backbone.View.extend({
    initialize: function() {
        if(this.model.get("parent_id"))
            this.$el.addClass("comment-reply");
    },
Homogeneity answered 22/9, 2018 at 8:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.