我正在使用带有Mustache的Backbone.JS,所以要渲染我的tempaltes,我调用MyModel.toJSON()。这使我只能访问属性。我怎样才能拥有一些始终计算的属性?
我查看了Backbone.JS文档,它可能会覆盖validate(),但这看起来像是一个黑客,可能导致无限循环。
我还尝试将属性设为函数而不是值,但是当我尝试使用它时,Mustache没有得到值。
答案 0 :(得分:3)
这就是我目前正在做的事情。我在初始化模型时进行计算,并为模型的更改添加一个监听器以自动重新计算。
...
initialize: function() {
console.log('Lead:initialize');
_.bindAll(this, 'validate', 'calculate');
this.bind('change', this.setCalculations, this);
this.setCalculations();
},
setCalculations: function() {
this.set({ calculations: this.calculate() }, { silent: true });
},
calculate: function() {
// do the calculations and return
},
...
答案 1 :(得分:0)
我不知道我是否正确理解了这个问题,但是:
你不能将实际模型传递给小胡子吗?例如,当你渲染
时render: ->
rendered_content = @template({model: @model})
$(@.el).html rendered_content
@
您正在将实际模型传递给模板。然后你有一个模板
<td class="quantity">
<input type="text" value="<%= model.get('quantity') %>" name="quantity" />
</td>
<td>
<%= model.getTotalPrice() %>
</td>
在模型中,您声明了getTotalPrice()
getTotalPrice: ->
total_price = @get('price') * @get('quantity')
total_price + total_price * @get('tax_rate')
我实际上从未在模板中传递@ model.toJSON,而是实际模型。