简体   繁体   English

如何等待所有商店在ExtJs中同步?

[英]How to wait until all stores are Sync in ExtJs?

I have a list of grids that can change their data in form by end-user. 我有一个网格列表,可以由最终用户更改其表单中的数据。 Finally, I want to sync all the grids by clicking the button, then an operation is performed. 最后,我想通过单击按钮同步所有网格,然后执行操作。

I wrote the code below: 我写了下面的代码:

$.when.apply(
    Ext.ComponentQuery.query('grid')
       .forEach(function(item) {
             if (item.getXType() == "grid") {
                if (item.store.getNewRecords().length > 0 || item.store.getUpdatedRecords().length > 0 || item.store.getRemovedRecords().length > 0) {
                    item.store.sync();
                 }
             }
})).then(function (results) {
    //do something
});

Problem is here that store.sync() not waiting for callback. 问题在于store.sync()没有等待回调。

What is the recommended way of doing this? 这样做的推荐方法是什么?

I do it with Promise like this: 我是这样做的Promise

 // Sync grid data if exist dirty data
 Promise.all(
     Ext.ComponentQuery.query('grid')
     .map(grid => grid.getStore())
     .filter(s => (s.getNewRecords().length + s.getUpdatedRecords().length + s.getRemovedRecords().length) > 0)
     .map(s => new Promise((resolve, reject) => {
           s.sync({
               success: () => { resolve(); },
               failure: () => { reject(); }
           });
      }))
      ).then(() => {
           //do something
      });

You could use callback for your store.sync() method. 您可以对store.sync()方法使用callback

The callback function to be called upon completion of the sync. 完成同步时调用的回调函数。 The callback is called regardless of success or failure and is passed the following parameters: (batch, options). 无论成功或失败,都会调用回调,并传递以下参数:(批处理,选项)。

You could achieve your requirement like this 你可以像这样达到你的要求

  1. Take a blank array name before loop. 循环前取一个空白数组名称。 like this var gridIds=[] . 像这样var gridIds=[]

  2. In side of loop before store.sync() push grid id in above array. store.sync()之前的循环中,在上面的数组中推送网格id。

  3. Now in callback function remove that grid id from above array and check condition array is blank then your all store sync response has came. 现在在callback函数中从上面的数组中删除该网格id并检查条件数组是否为空,然后您的所有商店同步响应已经到来。

You can check here with working Fiddle 你可以在这里查看工作小提琴

Note I have used dummy api. 注意我使用了虚拟api。 Please use your actual api. 请使用您的实际API。

CODE SNIPPET 代码链

Ext.application({
    name: 'Fiddle',

    launch: function () {

        Ext.define('MyStore', {
            extend: 'Ext.data.Store',

            alias: 'store.mystore',

            fields: ['name'],

            autoLoad: true,

            pageSize: 25,

            remoteSort: true,

            proxy: {
                type: 'ajax',
                method: 'POST',
                api: {
                    read: 'data.json',
                    update: 'your_update_api',
                    create: 'your_create_api',
                    destroy: 'your_delete_api'
                },
                reader: {
                    type: 'json'
                },
                writer: {
                    type: 'json',
                    encode: true,
                    root: 'data'
                }
            },
        });

        Ext.define('MyGrid', {

            extend: 'Ext.grid.Panel',

            alias: 'widget.mygrid',

            store: {
                type: 'mystore'
            },

            height: 200,

            border: true,

            tools: [{
                xtype: 'button',
                iconCls: 'fa fa-plus-circle',
                tooltip: 'Add New Record',
                handler: function () {
                    let grid = this.up('grid'),
                        store = grid.getStore();

                    store.insert(0, {
                        name: 'Test ' + (store.getCount() + 1)
                    });
                }
            }],
            columns: [{
                text: 'Name',
                dataIndex: 'name',
                flex: 1
            }]
        });

        Ext.create({
            xtype: 'panel',
            // title: 'Store sync example',

            items: [{
                xtype: 'mygrid',
                title: 'Grid 1'
            }, {
                xtype: 'mygrid',
                title: 'Grid 2'
            }, {
                xtype: 'mygrid',
                title: 'Grid 3'
            }, {
                xtype: 'mygrid',
                title: 'Grid 4'
            }],

            bbar: ['->', {
                text: 'Submit Changes',
                handler: function (btn) {
                    var panel = btn.up('panel'),
                        grids = panel.query('grid'),
                        gtidIds = [],
                        lenthCheck = function (arr) {
                            return arr.length > 0;
                        };

                    grids.forEach(function (grid) {
                        let store = grid.getStore();
                        if (lenthCheck(store.getNewRecords()) || lenthCheck(store.getUpdatedRecords()) || lenthCheck(store.getRemovedRecords())) {
                            panel.mask('Please wait...');
                            gtidIds.push(grid.getId());
                            store.sync({
                                callback: function () {
                                    Ext.Array.remove(gtidIds, grid.getId());
                                    if (gtidIds.length == 0) {
                                        panel.unmask();
                                        Ext.Msg.alert('Info', 'All grid store sync success.');
                                    }
                                }
                            }, grid);
                        }
                    });
                }
            }],
            renderTo: Ext.getBody(),
        })
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM