2016-06-07 115 views
1

當我通過const myRecord = this.store.createRecord('myType', myObject)創建記錄然後myRecord.save()時,請求通過適配器發送到服務器。數據成功保存,服務器將所有數據返回給客戶端。它通過串行器通過normalize()鉤子返回。EmberJs在保存後不更新記錄

問題是,當我刷新頁面灰燼不更新myRecord對象從服務器返回的屬性,例如idversion ......

,所有屬性都沒有(當然)。

我有更新記錄類似的問題。我的應用程序中的每個記錄都有一個由服務器檢查的版本屬性。每次保存時都會增加版本。這是爲了數據安全。問題是,當我嘗試多次更新記錄時,只有第一次嘗試成功。原因是在請求從服務器返回後version未更新。 (是的,服務器返回更新的版本)

這對我來說是一個令人驚訝的行爲,在我看來就像這裏建議的預期功能 - https://github.com/ebryn/ember-model/issues/265。 (但該帖子是從2013年開始的,並且建議解決方案對我來說不起作用)。

任何想法?

對於completenes,這裏是有關代碼(簡化的和重命名)

基於myModel

export default Ember.Model.extend({ 
    typedId: attr('string') // this serves as an ID 
    version: attr('string'), 
    name: attr('string'), 
    markup: attr('number'), 
}); 

myAdapter

RESTAdapter.extend({ 
    createRecord(store, type, snapshot) { 
     // call to serializer 
     const serializedData = this.serialize(snapshot, options); 

     const url = 'http://some_internal_api_url'; 
     // this returns a promise 
     const result = this.ajax(url, 'POST', serializedData); 

     return result; 
    }, 
}); 

mySerializer

JSONSerializer.extend({ 
    idAttribute: 'typedId', 

    serialize(snapshot, options) {  
     var json = this._super(...arguments); 
     // perform some custom operations 
     // on the json 
     return json; 
    }, 

    normalize(typeClass, hash) { 
     hash.data.id = hash.data.typedId; 

     hash.data.markup = hash.data.attribute1; 
     hash.data.version = parseInt(hash.data.version, 10); 

     return hash; 
    } 
}); 

回答

7

根本原因在串行器的normalize()方法中。 應該打電話給this._super.apply(this, arguments);,然後寫入Data Store中的更改。否則,它們不會反映在那裏。查看文檔http://emberjs.com/api/data/classes/DS.JSONSerializer.html#method_normalize

所以工作代碼看起來是這樣的

normalize(typeClass, hash) { 
     hash.data.id = hash.data.typedId; 

     hash.data.markup = hash.data.attribute1; 
     hash.data.version = parseInt(hash.data.version, 10); 

     return this._super.apply(this, [typeClass, hash.data]); 
    } 

最有可能你把這個版本

return this._super.apply(this, arguments); 
相關問題