由于@RP Niemeyer 回答中评论的问题,我刚刚实现了这个扩展器:
ko.extenders.confirmable = function(target, options) {
var message = options.message;
var unless = options.unless || function() { return false; }
//create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target();
//ask for confirmation unless you don't have
if (unless() || confirm(message)) {
target(newValue);
} else {
target.notifySubscribers(current);
}
}
}).extend({ notify: 'always' });
//return the new computed observable
return result;
};
然后,您可以将其应用于您的模型,如下所示:
var viewModel = {
myvalue: ko.observable(false).extend({confirmable: "Are you sure?"});
}
而且,如果有不要求确认的情况(在这个愚蠢的例子中,我们将在 3 月跳过确认),你可以这样做:
var viewModel = {
myvalue: ko.observable(false).extend({confirmable: { message: "Are you sure?", unless: function() { return new Date().getMonth() == 2 }} });
}