Dojo Диалог с кнопкой подтверждения

Я хотел бы добавить общий диалог с кнопками "Ok" и "Cancel" для поддержки функций обратного вызова.

Как я могу достичь этого с помощью Dojo AMD?

Например:

  myDialog = new Dialog ({

  title: "My Dialog",
  content: "Are you sure, you want to delete the selected Record?",
  style: "width: 300px",
  onExecute:function(){ //Callback function 
      console.log("Record Deleted") 
  },
  onCancel:function(){ 
      console.log("Event Cancelled") } 
  });
  // create a button to clear the cart
   new Button({ label:"Ok"
       onClick: myDialog.onExecute()
   }

   new Button({ label:"Cancel"
        onClick: function(){ myDialog.onCancel() }
   }

Ответы

Ответ 1

Вот решение, которое я придумал, когда столкнулся с тем же вопросом. Он не полностью программный, но использование шаблона делает код более читабельным и гибким для изменений.

Лучше видеть один раз, чем слышать 100 раз, поэтому см. весь код ниже в прямом эфире в jsFiddle: http://jsfiddle.net/phusick/wkydY/

Основным принципом, который я использую, является тот факт, что dijit.Dialog::content может быть не только строкой, но и экземпляром виджета. Поэтому я подклассу dijit.Dialog объявить класс ConfirmDialog. В ConfirmDialog::constuctor() я объявляю и создаю виджет из шаблона и устанавливаю его как диалоговое содержимое. Затем я провожу onClick действия в ConfirmDialog::postCreate():

var ConfirmDialog = declare(Dialog, {

    title: "Confirm",
    message: "Are you sure?",

    constructor: function(/*Object*/ kwArgs) {
        lang.mixin(this, kwArgs);

        var message = this.message;

        var contentWidget = new (declare([_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
            templateString: template, //get template via dojo loader or so
            message: message    
        }));
        contentWidget.startup();
        this.content = contentWidget;
    },

    postCreate: function() {
        this.inherited(arguments);
        this.connect(this.content.cancelButton, "onClick", "onCancel");
    }

})

Разметка шаблона:

<div style="width:300px;">

  <div class="dijitDialogPaneContentArea">
    <div data-dojo-attach-point="contentNode">
        ${message}              
    </div>
  </div>

  <div class="dijitDialogPaneActionBar">

    <button
      data-dojo-type="dijit.form.Button"
      data-dojo-attach-point="submitButton"
      type="submit"
    >
      OK
    </button>

    <button
      data-dojo-type="dijit.form.Button"
      data-dojo-attach-point="cancelButton"
    >
      Cancel
    </button>

  </div>

</div>

Теперь используйте ConfirmDialog вместо dijit.Dialog:

var confirmDialog = new ConfirmDialog({ message: "Your message..."});
confirmDialog.show();

Важно: Не забудьте отключить любые соединения с обратными вызовами диалоговых окон и уничтожить диалоговое окно при закрытии.

Если вы используете ConfirmDialog часто и в нескольких местах вашего кода, подумайте об этом:

var MessageBox = {};
MessageBox.confirm = function(kwArgs) {
    var confirmDialog = new ConfirmDialog(kwArgs);
    confirmDialog.startup();

    var deferred = new Deferred();
    var signal, signals = [];

    var destroyDialog = function() {
        array.forEach(signals, function(signal) {
            signal.remove();
        });
        delete signals;
        confirmDialog.destroyRecursive();
    }

    signal = aspect.after(confirmDialog, "onExecute", function() {
        destroyDialog();
        deferred.resolve('MessageBox.OK');
    });
    signals.push(signal);

    signal = aspect.after(confirmDialog, "onCancel", function() {
        destroyDialog();   
        deferred.reject('MessageBox.Cancel');            
    });
    signals.push(signal);

    confirmDialog.show();
    return deferred;
}

Ваш код будет более читабельным, и вам не придется заниматься очисткой:

MessageBox.confirm().then(function() {
    console.log("MessageBox.OK")
});

Ответ 2

Dojo 1.10 включает новый dijit/ConfirmTooltipDialog со встроенными кнопками "ОК" и "Отмена".

Ответ 3

Здесь как использовать dijit/ConfirmDialog и настроить его кнопки.

require(["dijit/ConfirmDialog"], function(ConfirmDialog){

    // create instance
    var dialog = new ConfirmDialog({
        title: "Session Expiration",
        content: "the test. Your session is about to expire. Do you want to continue?",
        style: "width: 300px"
    });

    // change button labels
    dialog.set("buttonOk","Yes");
    dialog.set("buttonCancel","No");

    // register events
    dialog.on('execute', function() { /*do something*/ });
    dialog.on('cancel', function() { /*do something*/ });

    // show
    dialog.show();
});

Ответ 4

Dojo Подтвердить диалог очень просто и полезно.
http://dojotoolkit.org/reference-guide/1.10/dijit/ConfirmDialog.html

require(["dijit/ConfirmDialog", "dojo/domReady!"], function(ConfirmDialog){
    myDialog = new ConfirmDialog({
        title: "My ConfirmDialog",
        content: "Test content.",
        buttonCancel: "Label of cancel button",
        buttonOk: "Label of OK button",
        style: "width: 300px",
        onCancel: function(){
            //Called when user has pressed the Dialog cancel button, to notify container.
        },
        onExecute: function(){
           //Called when user has pressed the dialog OK button, to notify container.
        }
    });
});