2014-10-11 70 views
0

在我的willTransition掛鉤中,我使用isDirty來確定模式是否應向用戶顯示一條警告,告知用戶如果他們離開,他們將丟失未保存的更改。問題是,在調整任何字段之前,Ember中的新記錄被認爲是髒的。我需要一種方法來覆蓋這種行爲。我試過以下沒有成功:如何將新記錄的髒污標記設置爲假

首先,我試着創建自己的標誌,觀察模型更改並將isNasty標誌設置爲true。我認爲這可能會起作用,因爲我忽略了.on('init'),但不幸的是這是立即設置爲新記錄。

// app/controllers/foo.js 
... 
isNasty: false, 

modelIsEdited: function() { 
    this.set('isNasty', true); 
}.observes('model') 

接下來,我想到了isDirty標誌的組合和isNew會做的伎倆,這並在技術上部分工作。但問題出現了,如果你再輸入字段插入新記錄,它永遠不會與模態提示:

// app/routes/foo.js 
... 
willTransition: function() { 
    if (this.controller.get('isDirty') && !this.controller.get('isNew') { 
    ... 
    } 
} 

同樣的問題提出了自己與dirtyType屬性(檢查它的created)。

最後,我嘗試在創建模型後手動將isDirty標誌設置爲false,但是因爲它是隻讀屬性,所以這也不起作用。

// app/routes/foo.js 
... 
setupController: function(controller, model) { 
    this._super(controller, model.demo); 
    controller.set('isDirty', false); 
    // This throws an error as isDirty is a read-only property 
} 
+0

所以你不希望用戶被警告,如果他們放棄他們正在創建的新模型? – Jakeii 2014-10-11 07:24:50

回答

1

從我個人理解,你想這樣:

if ((model.isDirty && !model.isNew) || (model.isNew && model.isFilledIn)) {} 

如果是這樣的話,我們已經有2出的3個狀態,所以我們只需要想出一個方法來創建isFilledIn狀態(或任何你想調用它)。我沒有在很長一段時間使用灰燼-數據,但我認爲這將工作:

isFilledIn: function() { 
    // `this._attributes` holds new values for attributes on the model. 
    // Because the model is new, all attributes are new, so if any 
    // attributes have been set, they'll be in here. 
    return Ember.keys(this._attributes) > 0; 
}.property().volatile() // don't try to observe this property 

現在你可以告訴我們,如果你的模型是舊的和修改,或者是新的,但有一些屬性設定。 (你必須爲關係做更多的工作。)

+0

謝謝,我基本上按照您的指示進行了一些修改。對於'if'語句中的每個'model'檢查,我使用'get()',所以'model.get('isDirty')'。然後return語句總是返回false,它似乎再次需要使用'this.get('_ attributes')'但是這仍然是false,所以我附加了'.length',因此整行結束爲'返回Ember.keys(this.get('_ attributes'))。length> 0;'。這解決了我的問題,謝謝! – 2014-10-14 18:20:05

相關問題