繁体   English   中英

在Ember中深度监视具有计算属性的任意JSON键

[英]Deep watch arbitriary JSON keys with computed properties in Ember

我有一个用例,其中Model具有用于任意配置的JSON属性: configuration: DS.attr()

我有一个configurationService (在每个组件/路由/控制器/ ...中初始化)具有计算属性,可以在整个应用程序中轻松检索此配置

由于JSON配置非常大并且具有可变深度,因此我不能为每一个配置具有计算属性

不幸的是, 作为服务的单例计算属性不会检测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}}}}} ,如果我以某种方式将randomConfig更改为true则不会检测到它

任何提示或替代品将不胜感激:)

更新:我尝试使用object Transform( 如Slack中所建议的 )并且它没有深入观察它: https//gist.github.com/benoror/272f0ae893f80276ac1553ae048e6b20#file-object-js

您需要将普通的JS-Object转换为Ember-Object,以及它的子对象:

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);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM