2016-10-03 58 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