【问题标题】:Ember computed property doesn't workEmber 计算属性不起作用
【发布时间】:2012-12-06 06:39:08
【问题描述】:

我有一个具有计算属性的视图。当依赖项被更新时,观察者会正确触发,但计算属性不会。可能是什么原因?

在车把中:

{{#view viewName currencyBinding="changingValue"}}
    {{view.prefix}}
{{/view}}

在视图中:

prefix: (function() {
  //does not get called!!! 
  console.log('computed property fired');
  return this.get('currency');
}).property('currency')

observeCurrency: (function() {
  //gets called!
  return console.log('observer fired');
}).observes('currency')

当 'changedValue' 更新但属性没有更新时,观察者会被触发! 另外,如果我在观察者中设置“前缀”:

observeCurrency: (function() {
    //gets called!
    console.log('observer fired');
    return this.set('prefix', this.get('currency'));
}).observes('currency')

除非我明确地重新呈现视图,否则我的 html 不会得到更新。为什么会这样?

【问题讨论】:

  • 除非我遗漏了一些你不必像这样包装你的计算属性的东西,它应该是 computedPropertyName: function { ... }.property('dependency')

标签: ember.js javascript-framework handlebars.js


【解决方案1】:

如果没有您的所有代码,很难说发生了什么,但让我们看看... 所以也许你应该像我在评论中所说的那样删除计算属性周围的包裹,这样你的视图就会有一个看起来像这样的属性:

SomeView: Em.View.extend({
    // other stuff...
    prefix: function() {
        console.log('prefix being called');
        // code that returns something goes here
    }.property('currency'),
    // other stuff...
})

现在我认为是问题所在,我制作了一个小提琴来模拟这种场景,在该场景中您指示您想要哪种货币,并且计算的属性具有确定前缀是什么的逻辑。 (可以看源码here)。

在您的代码中,当您绑定 changingValue 时,您并未指定此属性的来源,而是将 Ember 无法解析为应用程序中对象属性的路径传递。在我写的小提琴中,请注意属性 changingValue 属于我的应用程序(我将其命名为 SomeApp)。那么这个属性的路径是SomeApp.changingValue,我在把手中的绑定最终是:

{{view SomeApp.SomeView currencyBinding="SomeApp.changingValue"}}'

另外,请注意,在那个小提琴上,我创建了一个子视图,它将其content 属性与来自父视图的货币值绑定。我只在此处添加了它,因此您可以看到如果 您的代码 中的属性 changingValue 属于父视图,路径将如何。

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-06-09
    • 2015-08-19
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2012-08-04
    • 1970-01-01
    相关资源
    最近更新 更多