我有http://jsfiddle.net/ksCSn/1/
HTML
<input type="text" data-bind="
value: title,
hasfocus: edit,
onEnter: stopEdit" />
<p data-bind="text: title"></p>
JS
ko.bindingHandlers.onEnter = {
init: function(element, valueAccessor, _, viewModel) {
ko.utils.registerEventHandler(element, 'keydown', function(evt) {
if (evt.keyCode === 13)
valueAccessor().call(viewModel);
});
}
}
function ViewModel() {
this.title = ko.observable("default value");
this.edit = ko.observable(false);
this.stopEdit = function() {
this.edit(false);
// If the edit update is in a timeout, then it works
// var edit = this.edit;
// setTimeout(function() { edit(false); }, 0);
};
}
ko.applyBindings(new ViewModel());
为什么在输入字段中编辑时按回车键,值没有更新?
如果我更改编辑更新以使其作为超时排队,那么它就可以工作。这是为什么?
最佳答案
这是因为 Knockout 中的一个“错误”(参见 https://github.com/SteveSanderson/knockout/issues/321)导致所有绑定(bind)一起更新。当您更改 edit
属性时,它会更新 hasfocus
绑定(bind)以模糊字段,并且由于错误,还会更新 value
绑定(bind).因为绑定(bind)是按列出的顺序运行的,所以 value
绑定(bind)首先得到更新,这会在 View 模型中用 title
的值覆盖该字段。
修复此问题的一个简单更改是重新排序绑定(bind),以便 hasfocus
将首先运行:http://jsfiddle.net/mbest/ksCSn/8/
关于knockout.js 更改 hasfocus 值不会更新绑定(bind)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12384096/