Knockout and Click-to-Edit
A fiddle showing how to set up knockout bindings with minimal code to allow an HTML element to be editable when clicked.
by tlarson
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<!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>
JavaScript
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);