2012-03-05 18 views
1

我剛開始學習backbone.js,遇到了我的第一個問題。我想用attributes財產User視圖注入的屬性,而不是在我的模板本身寫他們的:Backbone.js在使用模板時無法合併屬性?

<div id="lista"></div> 

<script type="text/template" id="user-template"> 
    <a class="btn" href="#"><i class="icon-user"></i> 
    <%= first %> <%= last %></a> 
</script> 
window.UserView = Backbone.View.extend({ 
    attributes : { "data-route" : '/users/' + this.name }, 
    template: _.template($('#user-template').html()), 
    initialize : function() { 
     _.bindAll(this, "render"); 
    }, 
    render : function() { 
     $(this.el).html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 

var u = new User({ first : 'First', last : 'Last' }); 
var v = new UserView({ model : u, el : '#lista' }); 

v.render(); 

輸出缺少data-route屬性:

<div id="lista"> 
    <a href="#" class="btn"><i class="icon-user"></i> First Last</a> 
</div> 

你能否證實attributes不適用於template

回答

4

template使用作爲參數傳遞的哈希值,你的情況,你可以合併this.model.toJSON()this.attributes

嘗試

render: function() { 
    var data = _.extend(this.model.toJSON(), this.attributes); 
    this.$el.html(this.template(data)); 
    return this; 
} 
0

專門從文檔:

attributesmodel.attributes

屬性屬性是包含模型狀態的內部散列。請使用set來更新屬性,而不是直接修改它們。如果您想檢索並查看模型屬性的副本,請使用toJSON代替

相關問題