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

喜你入骨 提交于 2019-12-05 01:29:48

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
  }

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')
}

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'
})

I did it at View initialize

App.CommentView = Backbone.View.extend({
    initialize: function() {
        if(this.model.get("parent_id"))
            this.$el.addClass("comment-reply");
    },
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!