locked
[Code Snippet] Easy Chainable MessageDialog Composition

    General discussion

  • How about that for creating Windows.UI.Popups.MessageDialogs easier than with the original API?

    function messageDialog(content, title) {
      var addButton, dialog;
      dialog = new Windows.UI.Popups.MessageDialog(content, title);
      addButton = function(dialog, label, handler, object) {
        var command;
        dialog.commands.append(command = new Windows.UI.Popups.UICommand(label, handler, object));
        if (!object) {
          command.id = dialog.commands.length - 1;
        }
      };
      return {
        addButton: function(label, handler, object) {
          addButton(dialog, label, handler, object);
    return this; }, addCancelButton: function(label, handler, object) { dialog.cancelCommandIndex = dialog.commands.length; addButton(dialog, label, handler, object);
    return this; }, addDefaultButton: function(label, handler, object) { dialog.defaultCommandIndex = dialog.commands.length; addButton(dialog, label, handler, object);
    return this; }, title: function(title) { dialog.title = title; return this; }, content: function(content) { dialog.content = content; return this; }, cancelCommandIndex: function(index) { dialog.cancelCommandIndex = index; return this; }, defaultCommandIndex: function(index) { dialog.defaultCommandIndex = index; return this; }, showAsync: function() { return dialog.showAsync(); } }; };

    This allows you to write something like that:

    messageDialog("My Message", "With a Title")
    .addDefaultButton("Cool")
    .addCancelButton("Uncool")
    .addButton("I don't care")
    .showAsync()
    .then(function(button) {
      // button.id contains the index of the button by default
      // If you set the 'object' while creating the button, you will get that back in button.id then
    });

    I wonder, why the original API designers never facilitated such chaining? Is it incompatible with VB other projections?

    Enjoy!


    • Edited by pkursawe Wednesday, June 18, 2014 11:20 PM fixed code
    Wednesday, June 18, 2014 9:42 PM