簡體   English   中英

Backbone.js不包含視圖中的模型屬性

[英]Backbone.js don't include model properties in view

我在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

通常,您可以通過在模型屬性中指定模型的新實例來將模型與視圖相關聯,如下所示。然后,您可以將模型引用為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})

也沒有意識到該屬性是一個View屬性所以我不得不重命名我的模型和視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM