Having a user confirm a selection is a very common occurrence when an action is performed. In this Knockout js tutorial I’m going to demonstrate how to ask the user to confirm their choice. Only when the user has clicked OK will the observable value be changed. This example will leverage the ko.extender to create a custom Knockout extender.
Creating a custom Knockout js Extender
The common JavaScript code to ask a user to confirm a selection is to use the function confirm wrapped in an if statement as follows:
[code]
if (confirm(‘Do you want to proceed?’)) {
// Do action
}
[/code]
I am going to now leverage this inside a custom KO extender. Here is the full binding:
[code]
ko.extenders.confirmable = function (target, options) {
var message = options.message;
var unless = options.unless || function () { return false; }
var result = ko.computed({
read: target,
write: function (newValue) {
var current = target();
if (unless() || confirm(message)) {
target(newValue);
} else {
target.notifySubscribers(current);
}
}
}).extend({ notify: ‘always’ });
return result;
};
[/code]
To understand the inside, I’ll quickly demonstrate how this function is used. Inside your ViewModel when you are defining your ko observable, you apply a secondary function called extend as follows:
[code]
var myObservable = ko.observable().extend({
confirmable: {
message: “Are you sure you wish to continue?”
}
});
[/code]
Using the extend function you tell Knockout that you are implementing the confirmable function and are passing in a JavaScript object with a property called message with the string to be displayed in the confirm dialog.
In the custom ko extender, the observable – in this case – myObservable is wrapped in a ko.computed and when the user confirms your observable is set; otherwise, the variable myObservable is left unchanged.
As an added bonus, there is an extra parameter called unless that can be used to only call the confirm dialog when a specific condition is met. For example, perhaps you only want to ask for confirmation when a radio button is going from false to true. In this scenario, the definition can be changed as follows:
[code]
var myObservable = ko.observable().extend({
confirmable: {
message: “Are you sure you wish to continue?”,
unless: function() {
return myObservable();
}
}
});
[/code]
Because of this line: if (unless() || confirm(message)) the confirm dialog will only be called if the result of unless() is true.