JQuery UI Dialogs: application-wide options
Asked Answered
M

2

6

I have swarm of jquery-ui dialogs across my app. Every single time I need a new one, I write the following lines:

$('.another-dialog').dialog({
  title: 'Another dialog',
  autoOpen: false,
  draggable: true,
  modal: true,
  show: 'fade',
  hide: 'fade',
  width: 400,
  position: ['center', 'center'],
  buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ],
  open: function(event, ui) { $(".ui-dialog-titlebar-close span").html('×') }
});

The only things that are really differ between one dialog from another are the buttons and title keys. What I would like to have here is an application-wide setup for JQuery dialog, so the I would only call

$('.another-dialog').dialog({
  title: 'Another dialog',
  buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ]
});

with all the needed hash keys implicitly set up (i'd call it — "the default" setup).

I know I can wrap .dialog() call in, say, .myDialog() call where I'd set everything by myself. But I wonder if there's a true, convenient way of doing that.

Thanks in advance!

Mestee answered 12/8, 2011 at 14:53 Comment(1)
See this: #2287545Objective
G
5

You can put the common options in a variable (or in the data associated with the document if you want to use them from different scopes):

$(document).data("common-dialog-options", {
    autoOpen: false,
    draggable: true,
    modal: true,
    show: "fade",
    hide: "fade",
    width: 400,
    position: ["center", "center"],
    open: function(event, ui) {
        $(".ui-dialog-titlebar-close span").html("×");
    }
});

You can then use $.extend() to add the specific options for each dialog:

$(".another-dialog").dialog(
    $.extend({}, $(document).data("common-dialog-options"), {
        title: "Another dialog",
        buttons: [
            { text: "OK" },
            { text: "Cancel" }
        ]
    })
);
Gauhati answered 12/8, 2011 at 15:2 Comment(2)
Nice one. But why store it in the document's data. Why not just a global (or local to the main scope) variable?Cordalia
@Joseph, I personally prefer data() to global variables (mostly for namespace pollution reasons), and I cannot guarantee the questioner only has one "main" scope, so... :)Jessalyn
T
0
var defaultDialog = {
  title: 'Another dialog',
  autoOpen: false,
  draggable: true,
  modal: true,
  show: 'fade',
  hide: 'fade',
  width: 400,
  position: ['center', 'center'],
  buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ],
  open: function(event, ui) { $(".ui-dialog-titlebar-close span").html('×') }
};

var tunnedDialog= jQuery.extend(true, {}, defaultDialog );

tunnedDialog.title: 'Another dialog';
tunnedDialog.buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ]

$('.another-dialog').dialog(tunnedDialog);
Transom answered 12/8, 2011 at 15:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.