2016-10-03 22 views
0

我有一個模型具有用於任意配置的JSON屬性的用例:configuration: DS.attr()在Ember中使用計算屬性的深度監視任意JSON密鑰

我有一個configurationService(中的每個組件/路由/控制器初始化/ ...)具有用於整個應用程序

容易檢索這配置計算性能由於JSON配置是相當大&具有可變的深度我不能t對每一個人都有一個計算屬性

不幸的是,作爲服務單身人士計算出的屬性不檢測JSON密鑰(又名深度監視)中的變化。 我有辦法強制深入觀看JSON屬性

實施例:

服務/ configuration.js:

// These below can also be computed.alias, same effect 

configuration: Ember.computed(‘account.configuration', function() { 
    // account is set at application’s route: 
    // set(this, ‘configurationService.account', account); 
    return this.get(‘account.configuration’); 
}), 
profile: Ember.computed('configuration.profile', function() { 
    return this.get('configuration.profile'); 
}), 

任何/給定/ component.js:

configurationService: Ember.inject.service(‘configuration’), 
… 
// These won’t detect changes 
randomConfig: Ember.computed.alias(’configurationService.profile.foo.bar.randomConfig') 

考慮的配置目的是:{configuration: {profile: {foo: {bar: {randomConfig: false}}}}},如果我有點變化randomConfigtrue,它不會被檢測到

任何提示或替代方案,將不勝感激:)

UPDATE: 我有object嘗試變換(as suggested in Slack),並沒有深刻觀察它:https://gist.github.com/benoror/272f0ae893f80276ac1553ae048e6b20#file-object-js

+0

Can你給我們一個配置散列的預期大小和結構的意義嗎?您可能需要實現自己的方法來設置配置值,以將自定義事件發送給觀察配置屬性的任何人。您提供的關於使用方式的信息越多,建議方法越容易。 – maffews

+0

嘿@maffews,'''哈希'來自後端,可以是動態的和不可預測的,我無法預測最終形式,因爲應用程序將根據其內容動態適應。 –

+0

runspired提示使用的變換:https://embercommunity.slack.com/archives/-help/p1475469704021085 –

回答

0

您需要將普通的JS對象轉換爲Ember對象,因此對於其子對象:

import Ember from 'ember'; 
import DS from 'ember-data'; 

function emberify(obj) { 
    if(obj instanceof Array) { 
    return Ember.A(obj.map(i => emberify(i))); 
    } else if (obj instanceof Object) { 
    return Ember.Object.create(Object.keys(obj) 
     .reduce((hash, key) => { 
     hash[key] = emberify(obj[key]); 
     }, {})); 
    } 
} 

export default DS.Transform.extend({ 
    deserialize: function(value) { 
    return emberify(obj); 
    } 
} 
+0

我試圖與'餘燼.object.create',但深腕錶仍然不能正常工作:https://gist.github.com/benoror/272f0ae893f80276ac1553ae048e6b20#file-object-js –

+0

@BenOrozco你只創建一個'灰燼。用於頂層對象的對象,沒有深度嵌套。 – Lux