【问题标题】:Ember.js - Change what a computed property listens to at runtimeEmber.js - 更改计算属性在运行时监听的内容
【发布时间】:2013-07-19 13:48:30
【问题描述】:

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

例如

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

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

编辑

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

二次编辑

看起来这个问题已经在 github https://github.com/emberjs/ember.js/issues/1128 上解决过

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    此信息存储在内部变量_dependentKeys 中。你可能想要removeDependentKeys 之类的东西。但是,这是在立即函数中定义的,因此您将无法调用它。

    您可以根据需要复制逻辑,但考虑替代方案可能是个好主意。

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

    【讨论】:

    • +1 用于研究和源链接。我还没准备好接受,b / c我没有解决方案。不过谢谢!
    • 不用担心。我也很想找到能回答这个问题的人!因为那样他们也可以回答我的question。 :)
    【解决方案2】:

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

    ###
       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')
    

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 1970-01-01
      • 2013-06-29
      • 2015-09-08
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      相关资源
      最近更新 更多