A handler is added for the 'beforeclose' event. Due to the Ext MessageBox being asynchronous, the confirm box will show while the function returns false and cancels the 'close' event of the tab. If 'no' is selected (the user does not wish to save changes) then the tab is removed from it's parent container. Can be used to extend any type of component you are using in your tabpanel.
Hope this saves someone some time and trouble.
Ext.ConfirmPanel = Ext.extend(Ext.Panel, {
initComponent: function(){
Ext.ConfirmPanel.superclass.initComponent.apply(this, arguments);
this.addListener({
beforeclose:{
fn: this.onClose,
scope: this
}
});
},
onClose: function(p){
Ext.MessageBox.show({
title: 'Save changes?',
msg: 'Do you want to save changes?',
buttons: Ext.MessageBox.YESNOCANCEL,
fn: function(buttonId){
switch(buttonId){
case 'no':
this.ownerCt.remove(p); // manually removes tab from tab panel
break;
case 'yes':
this.saveToFile();
this.ownerCt.remove(p);
break;
case 'cancel':
// leave blank if no action required on cancel
break;
}
},
scope: this
});
return false; // returning false to beforeclose cancels the close event
}
saveToFile: function(){
//your code to save changes here
}
});
Ext.reg('confirmpanel', Ext.ConfirmPanel); // register the extension as an xtype
var yourTabPanel = new Ext.TabPanel({
activeTab: 0,
items: {
xtype: 'confirmpanel', // using the new xtype as your tab panel item will give the confirm function on closing
closable: true
}
});
Please leave a comment if this code helped you or if you have anything to add.
Thanks for this great snipet
ReplyDeleteIvan S
Thank you, I encountered this problem and used your solution, with some modifications.
ReplyDeleteThis is a ExtJS 4 version (sorry for bad code):
ReplyDeleteExt.define('Ext.ConfirmPanel', {
extend : 'Ext.Panel',
alias : 'widget.confirmpanel',
initComponent: function()
{
Ext.ConfirmPanel.superclass.initComponent.apply(this, arguments);
this.addListener({ beforeclose:{ fn: this.onClose, scope: this } });
},
onClose: function(p)
{
Ext.MessageBox.show({
title : 'Save changes?',
msg : 'Do you want to save changes?',
buttons : Ext.MessageBox.YESNOCANCEL,
fn : function(buttonId)
{
switch(buttonId) {
case 'no':
this.clearParameters();
this.ownerCt.remove(p);
break; // manually removes tab from tab panel
case 'yes':
this.saveToFile();
this.ownerCt.remove(p); break;
case 'cancel': break; // leave blank if no action required on cancel
}
},
scope: this
});
return false; /*returning false to beforeclose cancels the close event*/
},
clearParameters: function(){ /*your code to save changes here*/ },
saveToFile: function(){ /*your code to save changes here*/ }
});