Event Handling & Advanced Bindings
click
Binds a function to the click event of an element.
Example:
<button data-bind="click: myClickHandler">Click Me</button>
var viewModel = {
myClickHandler: function() {
alert('Button clicked!');
}
};
|
submit
Binds a function to the submit event of a form.
Example:
<form data-bind="submit: mySubmitHandler">
...
</form>
|
template
Renders a template with data from your view model. Templates can be inline or defined in separate script elements.
Example (Inline Template):
<div data-bind="template: { name: 'myTemplate', data: myData }"></div>
<script type="text/html" id="myTemplate">
<span data-bind="text: name"></span>
</script>
|
ko.bindingHandlers
Allows you to define your own custom bindings to encapsulate reusable UI logic.
Example:
ko.bindingHandlers.fadeVisible = {
init: function(element, valueAccessor) {
// Initially set the element to be instantly visible/hidden depending on the value
var shouldDisplay = valueAccessor();
$(element).toggle(shouldDisplay);
},
update: function(element, valueAccessor) {
// Whenever the value subsequently changes, slowly fade the element in or out
var shouldDisplay = valueAccessor();
shouldDisplay ? $(element).fadeIn() : $(element).fadeOut();
}
};
<div data-bind="fadeVisible: isVisible"></div>
|