Knockout and Click-to-Edit for Markdown
A fiddle showing how to set up knockout bindings with minimal code to allow an HTML element to be editable when clicked so that it can be a simple markdown editor
by tlarson
HTML
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="http://cdn.jsdelivr.net/foundation/4.1.2/css/foundation.min.css">
<script src="https://raw.githubusercontent.com/markdown-it/markdown-it/master/dist/markdown-it.min.js"></script>
<script src="https://raw.githubusercontent.com/grofit/knockout.markdown/master/src/knockout.markdown.js"></script>
<h4>Works Fine:</h4>
<label>Input Markdown:</label>
<textarea data-bind="value: text, valueUpdate: 'afterkeyup'"></textarea>
<label>Output (Computed):</label>
<div data-bind="html: md"></div>
<hr>
<label>Markdown (Click to Edit):</label>
<pre data-bind="text: text, visible: !editingText(), click: textClick"></pre>
<textarea data-bind="value: text, valueUpdate: 'afterkeyup', visible: editingText, hasfocus: editingText" type='text'"></textarea>
JavaScript
var ViewModel = function() {
var self = this;
self.editingText = ko.observable(false);
self.text = ko.observable('_Hello_ **World!**\n\n* Alpha\n* [Bravo](http://google.com)\n* Charlie\n');
self.md = ko.computed(function () {
var result = markdown.toHTML(self.text());
console.log("new computed: " + result);
return result;
});
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.
};
};
ko.applyBindings(new ViewModel());