Created
January 31, 2011 23:00
-
-
Save ajpiano/805016 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A RequireJS module that wraps the jQuery UI Dialog in a jQuery.Deferred | |
// Advantages: | |
// Reuses a single DOM element for all the dialogs | |
// Keeps the dialog out of the DOM when it is not in use | |
// A much more elegant interface for using custom modals and working with the user's resolution | |
define("bocoup.confirm",["jquery.ui.widget"],function(factory,position,dialog) { | |
var d = $("<div>"), | |
defaults = { | |
title:"Confirmation" | |
}; | |
function confirmation(question,options) { | |
options = $.extend({},defaults,options); | |
// Create a Deferred, an interface to which will be returned immediately upon the completion of the function | |
var dfd = jQuery.Deferred(), | |
dialogOptions = { | |
title:options.title, | |
modal:true, | |
buttons:{ | |
"Yes":function() { | |
// Resolve the Deferred, passing 'true' to indicate the user's choice | |
dfd.resolve(true); | |
d.dialog("close"); | |
}, | |
"No":function() { | |
// Close the dialog | |
d.dialog("close"); | |
} | |
}, | |
close:function() { | |
// Deferreds can only be resolved once. | |
// if the user chose "Yes," the Deferred will already have resolved, passing 'true' | |
// If the user chose "No," only then will the Deferred resolve 'false' | |
dfd.resolve(false); | |
d.dialog("destroy").remove(); | |
} | |
}; | |
} | |
// Return the Deferred's "promise," which allows the consumer of the code to observe - but not manipulate - the Deferred | |
return dfd.promise(); | |
}; | |
// The module returns an interface to use the confirmation | |
return confirmation; | |
}); | |
// Usage | |
require("bocoup.confirm",[],function(confirmation) { | |
$("#upgrade").click(function() { | |
// To create a custom modal confirmation that will react only when the user has decided yes or no, use the confirmation module | |
// The 'then' and 'fail' callbacks can be chained directly to the confirmation function, because it returns the promise interface | |
confirmation("Are you really sure you want to upgrade to jQuery 1.5?") | |
.then(function(confirmed) { | |
// Test to see how the deferred was resolved and act accordingly | |
if (confirmed) { | |
alert("Great Decision!"); | |
} else { | |
alert("I am truly sorry for your loss"); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment