Update 30.03.2018: Version 1.10 of dojotoolkit includes a dijit/DialogConfirm now, which is simply a dijit/Dialog featuring ‘OK’ and ‘Cancel’ buttons, no blocking though.
Update 15.10.2012: Code is available on githup now. I also fixed updating the content of the dialog after creation (e.g. dialog.set(‘content’, newContent) overwrote the confirm/cancel buttons because they were part of the content.
Update 03.12.2011: I updated the code to use dojo 1.7 with AMD. I also moved the creation of the Deferred to the show() method as suggested by ben, which will make the instance of the dialog reusable. Added new property hasUnderlay: true, which can be set to false.
JavaScript has a window.confirm() method, which opens a dialog and stops code execution until the user presses either the ‘OK’ or ‘Cancel’ button. Dojo also comes with a dijit.Dialog widget, but that doesn’t exhibit the same blocking behavior. Since I needed to simulate the native blocking behavior for an application I am currently developing, I extended the widget and created the DialogConfirm widget with the following features:
- shows an ‘OK’ and ‘Cancel’ button by default (can be set to false)
- shows a check box, which when set will remember the decision and not ask again (can be set to false)
- the show() method returns a dojo.Deferred() which allows you to simulate the code blocking
- underlay can be hidden
The demo of the DialogConfirm widget shows you how to halt code execution by just using the then() method of the returned deferred as follows:
var dialog = new snet.DialogConfirm({
title: 'Confirm',
content: '<p>Dialog content lore ipsum</p>'
});
dialog.show().then(function(remember) {
// user pressed ok button
// remember is true, when user wants you to remember his decision (user ticked the check box)
if (remember) {
// do something and never show this dialog again
}
else {
// do something
}
}, function() {
// user pressed cancel button
// do something
});