2016-09-29 85 views
0

這裏是設置一個計算屬性的從屬鍵在運行時

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是不需要的

另一件事是n逾時工作是

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

所以沒有任何一個知道如何設置一個計算屬性的依賴鍵在運行時,與計算依賴於模型實例

感謝

回答

0

在計算財產依賴鍵,只能是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'; 
     })); 
    } 
}); 
+0

非常感謝它的,你可以把一個函數調用來代替計算性能的依賴鍵的方式工作 – user2725682

+0

提供的呼叫沒有參數,並返回一個字符串。我首先嚐試了它,但它工作正常,但是當我需要爲此功能傳遞一個參數時,它不再起作用 – user2725682

+0

@ user2725682是的。你是對的..我更新了我的答案。如果需要,請使用已實施的解決方案查看我的答案。 – kumkanillam