Custom Binding sample
by pj_js15
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
<div data-bind="slideVisible: giftWrap, slideDuration:600">You have selected the option</div>
<label>
<input type="checkbox" data-bind="checked: giftWrap" />Gift wrap</label>
<script type="text/javascript">
var viewModel = {
giftWrap: ko.observable(true)
};
ko.applyBindings(viewModel);
</script>
JavaScript
ko.bindingHandlers.slideVisible = {
update: function (element, valueAccessor, allBindings) {
// First get the latest data that we're bound to
var value = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.unwrap(value);
// Grab some more data from another binding property
var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified
// Now manipulate the DOM element
if (valueUnwrapped === true) $(element).slideDown(duration); // Make the element visible
else $(element).slideUp(duration); // Make the element invisible
}
};