简体   繁体   中英

How can I get User confirm on combobox change event in ExtJs?

I have a combo in my extjs application and I want to show 'Are you sure?' confirm window to the user and prevent changing if user said no.

Since JavaScript's confirm box is synchronous, it works properly. But using Ext JS, the confirmation message is shown, and the rest of my code would be executed before user responds. Here is my code:

// JavaScript confirm box
{
    xtype: 'combo',
    ...
    ...
    ...
    listeners: {
        beforeselect: function(combo, record, index ) {
            if(confirm('Are you sure ?') == false)
            {
                 return false; // prevent combo from changing
            }
            // else continue
        }
    }
}
// Ext JS message box (to confirm)
{
    xtype: 'combo',
    ...
    ...
    ...
    listeners: {
        beforeselect: function(combo, record, index ) {
            Ext.Msg.show({
                title: 'Warning',
                msg: 'Are You Sure ?',
                buttons: Ext.Msg.YESNO,
                fn: function(btn) {
                    if (btn == 'yes') {
                        // continue and set new value on combo
                    }
                    else if (btn == 'no') {
                        // prevent combo from changing
                    }
                }
            });
        }
    }
}

The problem is the Ext.Msg.show gets a callback function and is not waiting for user answer and we're not able to prevent combobox changing.

What should I do?

In order to cancel the combobox change, the beforeSelect listener needs to return false. My suggestion is:

beforeselect: function(combo, record, index ) {
  Ext.Msg.show({
    title: 'Warning',
    msg: 'Are You Sure ?',
    buttons: Ext.Msg.YESNO,
    fn: function(btn) {
      if (btn == 'yes') {

        // Here we have to manually set the combo value
        // since the original select event was cancelled
        combo.setValue( /* whatever value was selected */ );
      }

      else if (btn == 'no') {

        // Don't do anything because the select event was already cancelled
      }
    }
  });

  // Cancel the default action
  return false;
}

The ExtJS Modal does not halt execution of the script like the native dialog, which means that the beforeSelect listener was returning prior to the user action. The way this code works is that the select event is immediately stopped, and the dialog shown. When the user selects "yes", then the value on the combo is programmatically set in the callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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