var clickToEditViewModel = function(text) { var self = this; self.editingText = ko.observable(false); self.text = ko.observable(text); self.textClick = function() { // Set editingText to true. This will cause the div to // hide, the input box to show, and the input box to // receive focus, all of which are bound to editingText. self.editingText(true); // Once the input box loses focus, editingText will be // set to false (due to binding), which will cause the // input box to hide and the div to show. }; }; var cteVM = new clickToEditViewModel("Hello World"); ko.applyBindings(cteVM);
<!DOCTYPE html> <html> <head></head> <body> <div class="well"> <h4>Click the text below to edit it. When done editing, click somewhere else.</h4> <span class="span1"> </span> <div data-bind="text: text, visible: !editingText(), click: textClick"></div> <input data-bind="value: text, visible: editingText, hasfocus: editingText" type='text'"></input> <br /> <h4>Here is another view of the text property on the viewmodel. This one is not set up for click-to-edit:</h4> <div data-bind="text: text"></div> </div> </body>