Ember.js-更改计算属性在运行时侦听的内容

Ember.js - Change what a computed property listens to at runtime

本文关键字:运行时 js- 计算 属性 Ember      更新时间:2023-09-26

有没有办法添加和删除计算属性在运行时侦听的属性?

例如

fullName: function(key, value) {
    //some code here
}.property('firstName', 'lastName')

我想在运行时删除"lastName"并添加"soupCan"。这可能吗?

编辑

进一步的信息:"soupCan"是在运行时生成的,我不能创建一个依赖它的属性b/c我不知道这个字符串会是什么。我没有空间或时间来解释这种设计模式,但这似乎是我们需要的一个边缘案例。

第二次编辑

看起来这以前已经在github上解决过了https://github.com/emberjs/ember.js/issues/1128

此信息存储在内部变量_dependentKeys上。你可能想要removeDependentKeys这样的东西。但是,这是在一个即时函数中定义的,所以你不能调用它

如果你愿意,你可以复制这个逻辑,但考虑其他选择可能是个好主意。

例如,您可以定义一个不同的计算属性fullNameSoup,它依赖于firstNamesoupCan,并在调用代码时在这些属性之间切换。或者将此切换逻辑封装到另一个计算属性中!

这是我解决这个问题的方法,但我很乐意接受任何提出更优雅解决方案的人请原谅我的咖啡脚本

###
   Add the property with the dynamic dependency key as a mixin after creating
   the dependency key in the context of the object
###
init: ->
    @_super()
    mix = Ember.Mixin.create({
        _fullName: (->
             @get('key_from_runtime') #some logic on this key goes here
        ).property(key_from_runtime)
    })
    mix.apply(@)
    @set('full_name_applied', true)
### Keep track of if the mixin has been applied ###
full_name_applied: false
### Depend on the shadow property that has the dynamic dependency key ###
fullName: (->
    if _.isNull(@get('_fullName'))
        '' #predefined blank value
    else
        @get('_fullName')
).property('_fullName', 'full_name_applied')