3

我的模板中有一个保存按钮,当模型 hasDirtyAttributes 时激活

当对相关模型的引用发生更改时,似乎没有设置 hasDirtyAttributes 标志。

示例
我有一个下拉菜单,允许选择一个名为contact
的相关模型。 如果我更改任何直接属性(例如名称),一切都会按预期工作,并且保存按钮会激活。
当我更改联系人时,它不会,我认为这是设计使然,所以我在更改操作被触发时设置了标志。

我在我的路由操作中设置它,如下所示:

actions:{ 

    updateProductionContact: function(contact){
         this.set('currentModel.customer.hasDirtyAttributes',true);             
         this.set('currentModel.customer.production_contact',contact);
    },
}

现在它又可以工作了。当我更改联系人时,保存按钮会亮起。
但是,当我现在单击保存时,hasDirtyAttributes 标志保持为真(按钮保持活动状态),而之前它被清除,直到进行另一次更改。

我希望框架在成功保存后自动重新设置标志,就像以前一样。我当然可以在按钮的保存操作上重新设置标志。

感觉就像我正在解决一个问题,也许 hasDirtyAttributes 不应该手动设置,或者我应该使用不同的肮脏指标。

我的问题:如何正确处理?

4

2 回答 2

1

事实证明 hasDirtyAttributes 是一个函数/计算属性。所以使用 set(...,true) 会用布尔值覆盖函数,这不是我们想要的。

ember 中的计算属性有一种方法可以拥有 setter 和 getter,但这似乎没有在这里实现。

我想出了以下解决方案。

基本上,这为相关模型实现了一个单独的自定义标志。

在路由的模型属性中,我定义了一个附加属性:

model: function(params) {
    return Ember.RSVP.hash({
       customer: this.store.findRecord('customer',params.id),
       ....
       dirtyRelations: false
    });
}, ...

然后我在更改相关模型时手动设置

updateProductionContact: function(contact){
     this.set('currentModel.dirtyRelations',true);             
     ...
}, ...

我的保存功能将其设置回 false。

updateCustomer:  function(){
     this.get('currentModel.customer').save();
     this.set('currentModel.dirtyRelations',false);
}

我的 template.hbs 检查 hasDirtyAttributes 或 dirtyRelations

{{#if (or model.customer.hasDirtyAttributes model.dirtyRelations)}}
    highlighted save
{{else}}
    plain save
{{/if}}

到目前为止,这似乎运作良好。我可以利用对正常属性的自动脏跟踪。

于 2017-06-16T08:50:53.577 回答
1

hasDirtyAttributes是的计算属性DS.Model所以你不应该手动设置它,如果你设置它,那么下次它不会再次重新计算。如果属性有任何变化,它将被更新。

就像评论中建议的 Alexma 一样,您可以使用dirtyAttributes. 参考https://guides.emberjs.com/v2.13.0/models/creating-updating-and-deleting-records/#toc_persisting-records 但不要自己设置。

参考: https ://github.com/emberjs/data/blob/v2.13.0/addon/-private/system/model/model.js#L162

于 2017-06-16T05:43:38.777 回答