2

如果我在模板中使用计算属性,我如何让模板知道状态已经以影响计算值的方式发生变化?

例如,如果我显示两个可以递增的数字及其总和,如下所示

App.ApplicationController = Ember.Controller.extend({
    x:0,
    y:0,
    sum: function(){return this.get("x") + this.get("y");}.property("content.sum"),
    incX: function(){ this.set("x", this.x+1);},
    incY: function(){ this.set("y", this.y+1);},
});
<script type="text/x-handlebars">
  <button {{action "incX"}}> {{x}} </button>
  <button {{action "incY"}}> {{y}} </button>
  <p> {{sum}} </p>
</script>

x 和 y 值将在显示中更新,但总和不会更新。我如何告诉车把/余烬总和取决于 x 和 y?

4

1 回答 1

5

计算属性 ( .property(_)) 的参数不是您想要访问的参数,而是指定计算属性在这些值中的任何一个发生变化时应该观察和重新计算的值。

在你的情况下:

sum: function() {
    return this.get("x") + this.get("y");
}
.property("x", "y")
于 2013-02-13T01:50:53.297 回答