不要在视图中包含模型属性

Backbone.js don't include model properties in view

本文关键字:包含 模型 属性 视图      更新时间:2023-09-26

我在Backbone.js中有一个模型,如下所示:

Attribute = Backbone.Model.extend({
    defaults: {
        label: '',
        values: {},
    },
});

这个视图:

AttributeView = Backbone.View.extend({
    tagName: 'button',
    className: 'btn',
    initialize: function(attribute) {
        this.attribute = attribute;
        this.render();
    },
    render: function() {
        var template = _.template($("#attribute-template").html(), {attribute: this.attribute});    
        this.$el.html(template);
    },
});
HTML模板:

<!----- attribute template ----->
<script type="text/template" id="attribute-template">
    <span class="attr">
        <%= attribute.get('label') %>
    </span>
    <span class="badge pull-right"></span>
</script>

结果是:

<button label="..." values="[object Object],[object Object],..." class="btn">...</button>

我的问题是为什么backbonejs添加标签和值属性到html模板,我怎么能防止这种情况?

你已经糟糕地选择了属性来保存你的模型(为什么你在自定义属性中存储你的模型也超出了我的范围),因为Backbone.View.attributes是一个属性,它意味着指定HTML属性添加到视图的el(这是你的<button>标签- http://backbonejs.org/#View-attributes.

通常,您可以通过在model属性中指定模型的新实例来将模型与视图关联起来,如下所示。然后您可以将模型引用为this.model,如果您只需要数据,则引用为this.model.toJSON():

AttributeView = Backbone.View.extend({
    model: new Attribute(),
    tagName: 'button',
    className: 'btn',
    initialize: function() {
        this.render();
    },
    render: function() {
        var template = _.template($("#attribute-template").html(), this.model.toJSON());    
        this.$el.html(template);
    },
});

供参考,这里有一个正确使用属性属性的例子:

AttributeView = Backbone.View.extend({
    model: new Attribute(),
    tagName: 'button',
    className: 'btn',
    attributes: {
        'data-foobar': "I'm a custom data attribute"
    }
    initialize: function() {
        this.render();
    },
    render: function() {
        var template = _.template($("#attribute-template").html(), this.model.toJSON());    
        this.$el.html(template);
    },
});

这将生成:

<button data-foobar="I'm a custom data attribute" class="btn">...</button>

原来我初始化视图时不正确。我直接传入模型

var itemView = new ItemView(item)

我需要将它声明为模型

var itemView = new ItemView({model: item})

也没有意识到属性是一个视图属性,所以我不得不重命名我的模型和视图