There's probably a way to do this with custom bindings, but here's a straightforward way to do it using the event
binding. You seem to imply that the observable should only change iif the enter key is pressed. However, I've added the blur
event as a trigger too; it's easy to remove that anyhow.
var ViewModel = function() {
var self = this;
self.zoomLevel = ko.observable('100');
self.newZoomLevel = ko.observable('100');
self.tryCommitZoomLevel = function(data, event) {
if (event.keyCode === 13 || event.type === "blur") {
self.zoomLevel(event.target.value);
}
// Make sure the event bubbles to let the value binding also handle events:
return true;
};
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="event: { keypress: tryCommitZoomLevel, blur: tryCommitZoomLevel }, value: newZoomLevel" />
<br />
The zoom level you've entered is: <strong data-bind="text: zoomLevel"></strong>%
The snippet keeps a seperate "new value" copy of the actual observable, and only commits it if the user presses enter or the input looses focus.