如何动态设置的className基于它的模型属性Backbone.js的一个看法? [英] How can I dynamically set a className for a Backbone.js view based on it's model attributes?

查看:132
本文介绍了如何动态设置的className基于它的模型属性Backbone.js的一个看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我需要的是做这样的事情。

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';
    }
  },

问题是,在这传递给的className 功能视图模板的HTML的上下文中执行,因此,我不能叫 this.model

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?

推荐答案

这听起来像模型绑定工作。

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
  }

这篇关于如何动态设置的className基于它的模型属性Backbone.js的一个看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆