假设用GridPanel和Store完成一个用户管理的功能,现在要删除在GridPanel中已选中的记录,在Controller中实现方式大致如下:
1 2 3 4 5 | var selModel = this.getGridPanel().getSelectionModel(); if(selModel.hasSelection()){ this.getGridStore().remove(selModel.getSelection()); this.getGridStore().sync(); } |
当第三行代码执行完的时候,GridPanel中我们选中的那些记录就已经消失了,然后第四行开始与服务器端同步(删除)数据,同步要么成功要么就是失败,同步成功的话是没有问题的,但是失败的话就出现问题了:UI上被移除的数据不会再出现了。
既然官方的API没有提供这样的功能,那就只能自己来实现了,在store的proxy中可以监听exception事件进行处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | listeners: { exception: function(proxy, response, operation, eOpts){ var error = operation.getError(); if(error.status){ error = error.status + ' ' + error.statusText; } Ext.Msg.show({title: '操作失败', msg: error, buttons: Ext.Msg.OK, icon: Ext.Msg.WARNING}); //如果是删除操作就恢复被删除的数据 if(operation.action == 'destroy'){ Ext.each(operation.records, function(record){ Ext.getStore('User').insert(record.lastIndex || 0, record); }); } } } |
现在删除失败的话就不会消失不出现了,但是新问题来了:
第一次删除u1失败了,然后u1被恢复,紧接着再删除u2也失败了,可以看到此时GridPanel中有两个u1和一个u2。
经过阅读Store源码发现里面有一个名为removed的数组,里面存放着所有的被删除的数据,在同步的时候要删除的数据就是从它里面取的,如果同步失败的话它不会被清空,就出现上面的问题了。
当然,不只是删除会出现这种问题,增加以及修改也存在这种问题。要处理的话还得去判断operation的action然后做相应的处理,而且定义的其它的Store都得这么来做,不如直接给官方那个Store增加一个数据恢复的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * @author Neeke * @date 2011-11-30 下午5:06:11 * @email root[at]ineeke.com * @function 给Store增加恢复数据的方法 */ Ext.data.Store.implement({ //恢复数据 restore: function(){ //恢复被删除的数据 Ext.each(this.removed, function(record){ this.insert(record.lastIndex || 0, record); }, this); //恢复被修改的数据 Ext.each(this.getUpdatedRecords(), function(record) { record.reject(); }, this); //删除新添加的数据 this.remove(this.getNewRecords()); //恢复所有数据到原始值 this.each(function(record) { record.reject(); }, this); this.removed = []; } }); |
用法:
1 2 3 4 5 6 7 8 9 10 | listeners: { exception: function(proxy, response, operation, eOpts){ var error = operation.getError(); if(error.status){ error = error.status + ' ' + error.statusText; } Ext.Msg.show({title: '操作失败', msg: error, buttons: Ext.Msg.OK, icon: Ext.Msg.WARNING}); Ext.getStore('User').restore(); } } |
现在再试试增删改全都没问题了。
除非另有声明,本站遵循【署名-非商业性使用-相同方式共享 3.0 共享协议】授权。
转载原创文章请注明,转载自:Neeke[http://www.ineeke.com]
本文链接: http://www.ineeke.com/archives/1412/
我都不懂。。
哈哈 多看看就懂了
回访罗,呵呵顶一个
因为不懂这个东西,只能支持下!
虽然看不懂,但是觉得很强大,支持一下朋友的分享精神。