问题
Please see the simple example below; a text box that is bound to a computed observable. My problem is that IE calls the write method twice when the text box is updated. Firefox and other browsers do not appear to have this problem. I have observed this issue in IE 7 & 8.
First of all, am I doing something wrong? If not, what is the recommended approach to deal with it?
<script>
var viewModel = {
myTestVar: "aaa"
};
viewModel.myTest = ko.computed({
read: function () {
return viewModel.myTestVar;
},
write: function (value) {
alert(value);
viewModel.myTestVar = value;
},
owner: viewModel
});
$(document).ready(function () {
ko.applyBindings(viewModel);
});
</script>
</head>
<body>
<input data-bind="value:myTest",type="text" style="width:150px;" />
</body>
回答1:
The value binding has a special section for dealing with auto-complete in Internet Explorer. This will often cause two writes. You can turn it off if you don't care about auto-complete by adding an attribute to the input:
<input data-bind="value:myTest" type="text" style="width:150px;" autocomplete="off" />
回答2:
Try this:
write: function (value) {
if(value != viewModel.myTestVar) {
alert(value);
viewModel.myTestVar = value;
}
}
Since viewModel.myTestVar is not an observable, I do not have a good idea why the write is called two times, but the check should prevent the actual multiple write.
来源:https://stackoverflow.com/questions/14903064/knockout-js-computed-observable-called-twice-in-internet-explorer