首页 > 解决方案 > ember hasDirtyAttributes 不适用于对象 (json)

问题描述

我有一个模型:

export default Model.extend({
  title: attr('string'),
  attributes: attr('jsonb')
});

存储在 Postgresattributes中的自定义文件在哪里。jsonjsonb

让我们说:

{
"name":"Bob",
"city":""
}

所以我可以很容易地attributes 使用模板
<form.element .. @property="attributes.city"/>model.set('attributes.city','city name')

问题hasDirtyAttributes不要改变,因为技术上我们有旧对象。但是当我尝试复制对象时,让说 JSON.parse(JSON.stringify(this.get('attributes')) hasDirtyAttributes按预期工作

那么如何为Mixin任何Model属性更改attribute将标记hasDirtyAttributestrue. 我将更新整个对象,因此实际上更改了哪个属性并不重要。

同样的问题:https ://discuss.emberjs.com/t/hasdirtyattributes-do-not-work-with-nested-attributes-json-api/15592

现有的解决方案对我根本不起作用:

更新:


一些不完美的想法有助于更好地描述我想要实现的目标:假设我们将观察者添加到任何对象fileds

export default Model.extend({
  init: function(){
    this._super();

    this.set('_attributes', Object.assign({}, this.get('attributes'))); //copy original 
    Object.keys(this.get('attributes')).forEach((item) => {
      this.addObserver('attributes.'+ item, this, this.objectObserver);
    });
  }
...
})

和观察者:

objectObserver: function(model, filed){
    let privateFiled = '_' + filed;

    if (model.get(privateFiled) != model.get(filed)) { //compare with last state
      model.set(privateFiled, this.get(filed));
      model.set('attributes', Object.assign({}, this.get('attributes')) );
    }

  }

这是可行的,但是当我由于复制对象而filed在每个文件上再次流线型时更改了一个。所以在这个关键改变每一个我标记观察归档为objectobjectObserverfiledobjectdirty

标签: jsonember.jsember-dataember-cli

解决方案


进一步的ember发展将减少事件监听器和双向绑定的使用,实际上 Glimmer 组件仅支持One-way Data Flow. ember因此,在这种情况下,对使用单向数据流的未来版本友好是一种很好的方法。所以就我而言,当我使用ember boostrap解决方案时,看起来像

<form.element @controlType="textarea" @onChange={{action 'attributeChange'}}

行动在哪里attributeChange都能发挥作用。

新的 Glimmer / Octane 样式基于modifier并且看起来像:

{{!-- templates/components/child.hbs --}}
<button type="button" {{on "click" (fn @onClick 'Hello, moon!')}}>
  Change value
</button>

推荐阅读