我有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());
为什么在输入字段中编辑时按下 Enter 键,值不更新?
如果我更改编辑更新,使其作为超时排队,那么它就可以工作。这是为什么?