尝试创建一个自定义绑定,它将检测两个输入框之一中的值何时发生变化,当它们发生变化时,我想启用“保存”按钮。最初,“保存”按钮被禁用。我似乎无法让它检测到事件,我试图在两个输入框上都使用 isDirty 标志,所以如果其中一个检测到更改,我会显示“保存”按钮。使用事件绑定来检测用户何时进行更改会更好吗?我认为自定义绑定会更好。isDirty 标志适用于我的错误消息显示。
HTML:
<span>Global Percentage:</span>
<input id="spaceGlobalPercentage" type="text" data-bind="value: globalPercent, valueUpdate: 'afterkeydown'" class="topInput" />
<span>Adjustment Factor:</span>
<input type="text" data-bind="value: adjustmentFactor, valueUpdate: 'afterkeydown'"class="topInput" />
<input type = "button" class="submitPercentCancelButton" id="submitPercentButton" value="Save" data-bind="click: save, enable: enableButton, buttonVisible: enableButton">
//自定义绑定
ko.bindingHandlers.buttonVisible = {
update: function (element, valueAccessor) {
//var value = valueAccessor(valueAccessor());
//var buttonUnwrapped = ko.utils.unwrapObservable(value);
var value1Unwrapped = ko.utils.unwrapObservable(valueAccessor(my.vm.globalPercent.isDirty));
var value2Unwrapped = ko.utils.unwrapObservable(valueAccessor(my.vm.adjustmentFactor.isDirty));
if (value1Unwrapped || value2Unwrapped ) {
my.vm.enableButton(true);
}
}
};
// 检查是否有变化
ko.subscribable.fn.trackDirtyFlag = function() {
var original = this();
this.isDirty = ko.computed(function() {
return this() !== original;
}, this);
return this;
};
// 视图模型
my.vm = {
globalPercent: ko.observable("").extend({ required: "Enter a Global Percent, between 1 and 100." }).trackDirtyFlag(),
adjustmentFactor: ko.observable("").extend({ required: "Enter an Adjustment Factor, between 1 and 100." }).trackDirtyFlag(),
enableButton: ko.observable(false),
..... };
// 应用绑定
ko.applyBindings(my.vm);
感谢您的任何建议或帮助