2016-11-30 27 views
0

我有一個模型User如下:嵌套的對象()`不受`DS.rollbackAttributes()`

import DS from 'ember-data'; 

const { attr, Model } = DS; 

export default Model.extend({ 
    name: attr("string"), 
    properties: attr(), 
}); 

User.properties旨在保持一個JSON對象。

我更新模型通過表單(使用ember-one-way-controls)如下:

{{one-way-textarea 
    model.name 
    update=(action (mut model.name))}} 

{{one-way-textarea 
    model.properties.description 
    update=(action (mut model.properties.description))}} 

我有一個按鈕,允許用戶通過調用discardChanges行動放棄修改:

actions: { 
    discardChanges(model) { 
    model.rollbackAttributes(); 
    }, 
}, 

name屬性更改正確丟棄/重置,但properties屬性不正確。

我該如何處理呢?

回答

1

問題

灰燼數據的由來是不知道的變化,因爲它使用===操作以比較原始的一個髒屬性。如果更改已被發現,Ember Data會將髒污屬性鍵存儲在_attributes陣列中。 We notice this here.然後,當您撥打DS.rollbackAttributes()時,模型會查看_attributes以確認要恢復的屬性。 Here it is.

但散列是不一樣的!

JS是所有關於通過引用傳遞值。下面是一個來自節點解釋器的示例:

> var foo = { description: 'hello' } 
undefined 
> var bar = foo; 
undefined 
> bar.description = 'bonjour'; 
'bonjour' 
> bar === foo 
true 

您正在修改原始對象。

解決方案

一個可能的解決方案是深複製你的properties對象並調用discardChanges時手動復位。

您可以實現IT即服務:

import Ember from 'ember'; 

const { copy, Service } = Ember; 

export default Service.extend({ 
    savedProperties: null, 

    finalize() { 
    this.set('savedProperties', null); 
    }, 

    start(model) { 
    const properties = copy(model.get('properties')); 
    this.set("savedProperties", properties); 
    }, 

    undo(model) { 
    const savedProperties = this.get('savedProperties'); 
    for (const property in savedProperties) { 
     if (savedProperties.hasOwnProperty(property)) { 
     const keyPath = `properties.${property}`; 
     model.set(keyPath, savedProperties[property]); 
     } 
    } 
    this.set('savedProperties', null); 
    }, 
}); 
  • 你叫start當您在編輯模式下輸入。
  • 當你想放棄更改你叫undo
  • 你叫finalize當你成功保存您的記錄。
+0

你也可以正確地稱這是一個錯誤,從一開始它已經存在。關於SO的問題一直是許多問題的主題。底線是你有人需要自己管理骯髒的子對象; 'notifyPropertyChange'是一個選項,如果現在還不推薦使用。 – 2016-12-20 15:17:35