Store do something after sync with autoSync enabled

▼魔方 西西 提交于 2019-11-28 22:07:33
Izhaki

This is, if you ask me, some design flaw in ExtJS.

AbstractStore has onCreateRecords, onUpdateRecords, and onDestroyRecords, which are empty functions you can override. You can call rejectChanges() if success is false there.

Ext.define('BS.store.Users', {
    extend: 'Ext.data.Store',    
    model: 'BS.model.User',

    autoSync: true,
    autoLoad: true,

    proxy: {
        type: 'direct',
        api: {
            create: Users.Create,
            read: Users.Get,
            update: Users.Update,
            destroy: Users.Delete,

        },
        reader: {
            type: 'json',
            root: 'data',
        },
    },

    onCreateRecords: function(records, operation, success) {
        console.log(records);
    },

    onUpdateRecords: function(records, operation, success) {
        console.log(records);
    },

    onDestroyRecords: function(records, operation, success) {
        console.log(records);
    },

});

FYI: Sequence of events when updating a record (ExtJs 5.0.1)

Scenerio 1
javascript executes 
record.set('some data')  // Store has autoSync: true, The database will succeed

'update' event fires (operation = 'edit')
'beforesync' event fires
network traffic occurs database returns a success (json)
'update' event fires (operation = 'commit') 
'onUpdateRecord' method runs

Scenerio 2
javascript executes
record.set('some data')  // Store has autoSync: true, The database will fail

'update' event fires (operation = 'edit')
'beforesync' event fires
network traffic occurs database returns a failure (json)
'onUpdateRecord' method runs and calls rejectChanges()
'update' event fires (operation = 'reject') 
'exception' event fires

Two Notes: a) the last update and onUpdateRecord are reversed and b) if the onUpdateRecord does not call rejectChanges() the following 'update' event is not fired. This will leave the record in a dirty state which means that subsequent sync() will send it.

For record.add() the events are similar however I see that the 'add' event is not fired. The Ext documentation for the event says that it is fired but the same documentation does not say that the add() method will fire the event.

Another way to get around this is to use suspendAutoSync and resumeAutoSync methods of the store and then manually sync (Ext JS > 4.1.0):

store.suspendAutoSync();
store.insert(0, record);
store.sync({
   success: function (batch, options) {
      // do something
   },
   failure: function (batch, options){
      // handle error
   }
});
store.resumeAutoSync();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!