Search code examples
javascriptalertifyjs

Is it possible to separate the actions called by the cancel button and the onclose for alertify.js


I currently have this:

            $('form#uwbhandler').on('click', function(e){
            e.preventDefault();
            alertify.confirm("Mode 1",
              function(){
                alertify.success('Sent: Success Something');
                socket.emit('send command', {data: 'acommand'});
              },
              function(){
                alertify.success('Sent: Something');
                socket.emit('send command', {data: 'bcommand'});
              }).setHeader('<em>Select Mode</em> ').setting('labels',{'ok':'Mode 1', 'cancel': 'Mode 2'}).set({onshow:null, onclose:function(){ alertify.message('confirm was closed.')}});;
        });

Which is mostly taken from the example on the alertify.js page. However, I want to customize the cancel button action separate from the onclose button. However, closing with the "x" button for the dialog fires the cancel event event after setting a separate onclose function.


Solution

  • I recommend using the Dialog Factory to create your custom dialog.

    The confirm dialog definition is set to invoke the cancel action upon closing the dialog.

    However, A quick solution would be to inherit from the existing confirm dialog and update its setup to disable invokeOnClose:

    alertify.dialog('myCustomDialog', function() {
      return {
        setup: function() {
          return {
            buttons: [{
              text: 'Mode 1',
              key: 13 /*keys.ENTER*/ ,
              className: alertify.defaults.theme.ok,
            }, {
              text: 'Mode 2',
              key: 27 /*keys.ESC*/ ,
              invokeOnClose: false, // <== closing won't invoke this
              className: alertify.defaults.theme.cancel,
            }],
            focus: {
              element: 0,
              select: false
            },
            options: {
              title: '<em>Select Mode</em> ',
              maximizable: false,
              resizable: false
            },
          };
        }
      }
    }, false, 'confirm');
    

    Then use a local variable to decide whether to execute the logic inside the onclose callback:

    function demo() {
      var modeSelected = false;
      alertify.myCustomDialog("Which mode will it be?",
          function() {
            modeSelected = true;
            alertify.success('Mode 1');
          },
          function() {
            modeSelected = true;
            alertify.success('Mode 2');
          }
        )
        .set({
          onshow: null,
          onclose: function(arg) {
            if (!modeSelected) {
              alertify.message('confirm was closed.');
            }
            modeSelected = false;
          }
        });
    }
    

    see live demo