Skip to content

Instantly share code, notes, and snippets.

@rogersillito
Created November 17, 2015 17:30
Show Gist options
  • Save rogersillito/a3b0e7fe4f0142fbd2cf to your computer and use it in GitHub Desktop.
Save rogersillito/a3b0e7fe4f0142fbd2cf to your computer and use it in GitHub Desktop.
knockout.js: experimenting with bindings (css, checked, textInput, if)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div data-bind="html: someHtml, css: cssClass"></div>
<p>showStuff? <input type="radio" name="iv" data-bind="checkedValue: true, checked: showStuff" value="true" /> yes
<input type="radio" name="iv" data-bind="checkedValue: false, checked: showStuff" value="false" /> no
</p>
<p>cssClass: <input type="text" data-bind="value: cssClass, enable:showStuff" /></p>
<p>cssDefinitions: <textarea cols="40" rows="15" data-bind="textInput: cssDefinitions"></textarea></p>
<div data-bind="if: showStuff" style="white-space: pre; font-family: Courier">
<p data-bind="text: cssDefinitions().trim()"></p>
<p data-bind="text: showStuff"></p>
</div>
<script id="jsbin-javascript">
var TestViewModel = function() {
var self = this;
self.showStuff = ko.observable(true);
self.someHtml = ko.observable("<strong><em>&quot;Lovely HTML!&quot;</em></strong> (to demo the <u>html</u> and <u>css</u> bindings)");
self.cssClass = ko.observable();
self.cssDefinitions = ko.observable(".red {\n color: #f00;\n}\n.green {\n color: #090;\n}");
self.computedCss = ko.computed(function(){
var cssEl="<style>"+self.cssDefinitions()+"</style>";
$('head').append(cssEl);
});
};
ko.applyBindings(new TestViewModel());
</script>
<script id="jsbin-source-javascript" type="text/javascript">var TestViewModel = function() {
var self = this;
self.showStuff = ko.observable(true);
self.someHtml = ko.observable("<strong><em>&quot;Lovely HTML!&quot;</em></strong> (to demo the <u>html</u> and <u>css</u> bindings)");
self.cssClass = ko.observable();
self.cssDefinitions = ko.observable(".red {\n color: #f00;\n}\n.green {\n color: #090;\n}");
self.computedCss = ko.computed(function(){
var cssEl="<style>"+self.cssDefinitions()+"</style>";
$('head').append(cssEl);
});
};
ko.applyBindings(new TestViewModel());</script></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment