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 snet.DialogConfirm widget:
- 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
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
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
});