尝试创建一个自定义绑定,它将检测两个输入框中的一个值何时发生变化,当它们发生变化时我想启用“保存”按钮。最初,“保存”按钮被禁用。 我似乎无法检测到事件,我正在尝试在两个输入框上使用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),
..... };
// apply bindings
ko.applyBindings(my.vm);
感谢您的任何建议或帮助
答案 0 :(得分:0)
在这种情况下,似乎自定义绑定可能太多了。我会根据每个字段的ko.computed
状态使用isDirty
:
var 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(),
save: function () {
alert('saved');
}
};
vm.enableButton = ko.computed(function () {
return this.globalPercent.isDirty() || this.adjustmentFactor.isDirty();
}, vm);