除了內建的click, value之外,
knockout.js 也可以自行建立新的綁定。
ko.bindingHandlers.slideVisible = {
update: function(element, valueAccessor, allBindingsAccessor) {
// First get the latest data that we're bound to
var value = valueAccessor(), allBindings = allBindingsAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.utils.unwrapObservable(value);
// Grab some more data from another binding property
var duration = allBindings.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
}
};
<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>