knockout.js Computed observable called twice in Internet Explorer

南笙酒味 提交于 2019-12-13 15:06:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!