查看渲染:是否有更好的方法来控制视图元素的类名?

rkw*_*rkw 1 backbone.js

var myView = Backbone.View.extend({
    tagName: 'div',
    className: function() {
        return this.model.isNew() ? 'new' : 'old';
    }
Run Code Online (Sandbox Code Playgroud)

这是我想要的功能,但它不起作用.我不确定何时确定类名,但被调用者只是元素本身; 在这种情况下,它会<div></div>.有没有办法让className访问模型?

我可以,并且目前,在我的模板中放置另一个div,以便控制类,但如果我能够从View本身控制类名,则绝对不需要div.

Rob*_*ska 6

如果是我,我可能会在render()使用辅助函数时设置该类类型:

var myView = Backbone.View.extend({
    render: function() {
        this.applyClass();
        return this;
    },

    applyClass: function() {
        var isNew = this.model.isNew();
        $(this.el)
            .toggleClass('new', isNew)
            .toggleClass('old', !isNew);
    }
});
Run Code Online (Sandbox Code Playgroud)

applyClass如果需要,您可以稍后在事件处理程序中重用:

    initialize: function(options) {
        this.model.bind('change', this.applyClass, this);
    }
Run Code Online (Sandbox Code Playgroud)