【问题标题】:set the dependent keys of a computed property at run time在运行时设置计算属性的依赖键
【发布时间】:2017-02-07 17:26:24
【问题描述】:

这里是场景

dep = function(){

     cannot put any "this" here
}

obj =  DS.Model.extend({
        response: DS.attr(),
        cp: Ember.computed(dep(), function(){ ...})
    });

计算属性只有在模型加载后才知道;响应是一个 json 字段,包含各种键。我想依赖 json 的某些部分,加载模型后知道确切的部分

dep() 函数需要访问“this”,但如果它是在 create 指令之外定义的,它就不起作用,如果它被定义为计算属性,它也不起作用 比如

obj =  DS.Model.extend({
    response: DS.attr(),
    dep:Ember.computed('response', function(){ 
     some computation 
     and for instance 
     return 'response.path1{a,b}';
     }),
    cp: Ember.computed('dep', function(){ ...})
});

也不起作用,因为 dep 并没有从“响应”依赖改变,我们需要对 cp 和 dep 应用相同的依赖,这是重言式的,并且不需要 dep

另一件不起作用的是

  obj =  DS.Model.extend({
            response: DS.attr(),
            cp: Ember.computed(this.dep(), function(){ ...}),
            dep(){    this.get('response')...  }
        });

那么有谁知道如何在运行时设置计算属性的依赖键,计算依赖于模型实例

谢谢

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    在计算属性依赖键中,只能是string 或任何返回string 的全局函数,但不能访问函数内部的this 上下文。

    我建议将 cpModel 移到其他位置。

    在模型就绪钩子中,您可以创建动态计算属性并从response 设置依赖键。

    下面的代码可能会帮助您找到解决方案。我没做过,你可以试试看。

    import DS from 'ember-data';
    export default DS.Model.extend({
        response: DS.attr(),
        ready() {
            this._super(...arguments);
            var response = this.get('response');
            //you can write dep() logic here and contstruct dynamic key . You will have access to this context here.
            var newDynamicKey = 'response.path1{a,b}';
            Ember.defineProperty(this, 'cp', Ember.computed(newDynamicKey, function() {
                //do your work and return result
                return 'result';
            }));
        }
    });
    

    【讨论】:

    • 顺便说一句,如果调用没有参数并返回一个字符串,您可以将函数调用代替计算属性的依赖键。我先尝试了它,它工作了,但是当我需要为这个函数传递一个参数时它不再工作了
    • @user2725682 是的。你是对的..我更新了我的答案。如果需要,请使用您实施的解决方案查看我的答案。
    猜你喜欢
    • 2020-05-21
    • 2011-05-12
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    相关资源
    最近更新 更多