Установить обратный вызов AlertifyJS при отображении диалога - PullRequest
0 голосов
/ 21 февраля 2019

Я использую AlertifyJS, чтобы показать пользовательскую форму и сделать вызов, чтобы изменить несколько записей.Я определил функцию для отображения диалогового окна:

function showDialog(title, formDialog, callbackfunction, params) {
    alertify.dialog('customModal', function factory() {
        var placeholder = null
        return {
            main: function (content) {
                if (content instanceof HTMLElement && content.parentNode) {
                    placeholder = placeholder || document.createComment('')
                    content.parentNode.insertBefore(placeholder, content)
                }
                this.setContent(content);
            },
            setup: function () {
                return {
                    /* buttons collection */
                    buttons: [
                        /*button defintion*/
                        {
                            /* button label */
                            text: 'OK',
                            /*bind a keyboard key to the button */
                            key: 27,
                            /* indicate if closing the dialog should trigger this button action */
                            invokeOnClose: false,
                            /* custom button class name  */
                            className: alertify.defaults.theme.ok,
                            /* custom button attributes  */
                            //attrs: { buttonValue: 'submit' },
                            /* Defines the button scope, either primary (default) or auxiliary */
                            scope: 'auxiliary',
                            /* The will conatin the button DOMElement once buttons are created */
                            element: undefined
                        },
                        {
                            /* button label */
                            text: 'Cancel',
                            /*bind a keyboard key to the button */
                            //key: 27,
                            /* indicate if closing the dialog should trigger this button action */
                            invokeOnClose: false,
                            /* custom button class name  */
                            className: alertify.defaults.theme.cancel,
                            /* custom button attributes  */
                            //attrs: { buttonValue: 'submit' },
                            /* Defines the button scope, either primary (default) or auxiliary */
                            scope: 'auxiliary',
                            /* The will conatin the button DOMElement once buttons are created */
                            element: undefined
                        }
                    ],
                    options: {
                        basic: false,
                        maximizable: false,
                        resizable: false,
                        padding: false,
                        closableByDimmer: false,
                        title: 'My custom dialog'
                    }
                };
            },
            callback: function (closeEvent) {
                //The closeEvent has the following properties
                //
                // index: The index of the button triggering the event.
                // button: The button definition object.
                // cancel: When set true, prevent the dialog from closing.
                console.log(closeEvent);
                if (closeEvent.index == 0) { //OK Button
                    callbackfunction(params);
                }
            },
            hooks: {
                onclose: function () {
                    if (placeholder != null) {
                        var node = this.elements.content.firstElementChild
                        node.style.display = 'none'
                        placeholder.parentNode.insertBefore(node, placeholder)
                    }
                }
            }
        };
    });

    alertify.customModal($(formDialog)[0]).set('title', title);
    $(formDialog).show();
}

Эта функция вызывает проблему с сообщением "alerttify.dialog: имя уже существует".Я только что переместил объявление диалога в функцию document.ready вне этой функции, но я не знаю, как передать функцию обратного вызова:

$(document).ready(function () {
    alertify.dialog('customModal', function factory() {
        var placeholder = null
        return {
            main: function (content) {
                if (content instanceof HTMLElement && content.parentNode) {
                    placeholder = placeholder || document.createComment('')
                    content.parentNode.insertBefore(placeholder, content)
                }
                this.setContent(content);
            },
            setup: function () {
                return {
                    /* buttons collection */
                    buttons: [
                        /*button defintion*/
                        {
                            /* button label */
                            text: 'OK',
                            /*bind a keyboard key to the button */
                            key: 27,
                            /* indicate if closing the dialog should trigger this button action */
                            invokeOnClose: false,
                            /* custom button class name  */
                            className: alertify.defaults.theme.ok,
                            /* custom button attributes  */
                            //attrs: { buttonValue: 'submit' },
                            /* Defines the button scope, either primary (default) or auxiliary */
                            scope: 'auxiliary',
                            /* The will conatin the button DOMElement once buttons are created */
                            element: undefined
                        },
                        {
                            /* button label */
                            text: 'Cancel',
                            /*bind a keyboard key to the button */
                            //key: 27,
                            /* indicate if closing the dialog should trigger this button action */
                            invokeOnClose: false,
                            /* custom button class name  */
                            className: alertify.defaults.theme.cancel,
                            /* custom button attributes  */
                            //attrs: { buttonValue: 'submit' },
                            /* Defines the button scope, either primary (default) or auxiliary */
                            scope: 'auxiliary',
                            /* The will conatin the button DOMElement once buttons are created */
                            element: undefined
                        }
                    ],
                    options: {
                        basic: false,
                        maximizable: false,
                        resizable: false,
                        padding: false,
                        closableByDimmer: false,
                        title: 'My custom dialog'
                    }
                };
            },
            callback: function (closeEvent) {
                //The closeEvent has the following properties
                //
                // index: The index of the button triggering the event.
                // button: The button definition object.
                // cancel: When set true, prevent the dialog from closing.
                console.log(closeEvent);
                if (closeEvent.index == 0) { //OK Button
                    callbackfunction(params);
                }
            },
            hooks: {
                onclose: function () {
                    if (placeholder != null) {
                        var node = this.elements.content.firstElementChild
                        node.style.display = 'none'
                        placeholder.parentNode.insertBefore(node, placeholder)
                    }
                }
            }
        };
    });

    });
function showDialog(title, formDialog, callbackfunction, params) {

    alertify.customModal($(formDialog)[0]).set('title', title); //pass callback function here
    $(formDialog).show();
}

Спасибо

1 Ответ

0 голосов
/ 22 февраля 2019

Вам необходимо отделить создание диалога от его создания, как уже упоминалось в комментариях !alertify.customModal && alertify.dialog('customModal'.... гарантирует, что диалог создается только один раз.

Это создаст одноэлементное диалоговое окно, поэтому вам нужно передать обратный вызов в качестве параметра, либо в функции main, либо в качестве настроек, а затем вызвать его в функции модального обратного вызова:

!alertify.customModal && alertify.dialog('customModal', function factory() {
  var placeholder = null
  return {
    main: function (content, callback) {
    ....
    //sets callback
    this.set('callback', callback);
  },
  settings: {
    ....,
    callback:undefined //holds callback ref
  },
  callback: function (closeEvent) {
    //invokes callback if set
    var cb = this.get('callback')
    if (typeof cb === 'function') {
      var returnValue = cb.call(this, closeEvent);
      if (typeof returnValue !== 'undefined') {
        closeEvent.cancel = !returnValue;
      }
    }
  }
});

Затем назовите ваш пользовательский модал:

function showDialog(title, formDialog, callbackfunction, params) {
  alertify.customModal($(formDialog)[0], callbackfunction)
          .set('title', title); //pass callback function here
}

Я включил только соответствующие части для удобства чтения.

Для полного примера, посмотрите на реализацию встроенных диалогов: Предупреждение , Подтверждение и Подсказка .

...