Skip to content

Instantly share code, notes, and snippets.

@rogersillito
Created November 14, 2015 21:39
Show Gist options
  • Save rogersillito/b425af90e5fab9c8aabf to your computer and use it in GitHub Desktop.
Save rogersillito/b425af90e5fab9c8aabf to your computer and use it in GitHub Desktop.
knockout.js: experimenting with custom binding handlers
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style id="jsbin-css">
h1 { display: block; }
</style>
</head>
<body>
<h1 data-bind="text: greeting, subheading: extra()"></h1>
<input type="text" data-bind="value: extra" />
<script id="jsbin-javascript">
var TestViewModel = function() {
this.greeting = "Hello World";
this.extra = ko.observable("Some default text.");
};
$(document).ready(function() {
var log = console.log.bind(console);
ko.bindingHandlers.subheading = {
init: function(element, valueAccessor){
var newText = valueAccessor();
log('init:', newText);
$(element).after('<h2>'+newText+'</h2>');
},
update: function(element, valueAccessor){
var newText = valueAccessor();
log('updating:', newText);
var $subHeader = $(element).next('h2');
$subHeader.fadeOut();
//debugger;
setTimeout(function() {
$subHeader.text(newText);
$subHeader.fadeIn();
}, 400);
}
};
ko.applyBindings(new TestViewModel());
});
</script>
<script id="jsbin-source-css" type="text/css">h1 { display: block; }</script>
<script id="jsbin-source-javascript" type="text/javascript">
var TestViewModel = function() {
this.greeting = "Hello World";
this.extra = ko.observable("Some default text.");
};
$(document).ready(function() {
var log = console.log.bind(console);
ko.bindingHandlers.subheading = {
init: function(element, valueAccessor){
var newText = valueAccessor();
log('init:', newText);
$(element).after('<h2>'+newText+'</h2>');
},
update: function(element, valueAccessor){
var newText = valueAccessor();
log('updating:', newText);
var $subHeader = $(element).next('h2');
$subHeader.fadeOut();
//debugger;
setTimeout(function() {
$subHeader.text(newText);
$subHeader.fadeIn();
}, 400);
}
};
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