I have the following KnockoutJS template (render with jquery.tmpl):
<script id="contactsTemplate" type="text/html">
<li data-bind="click: contactViewModel.test">${DisplayName}</li>
</script>
<ul id="contact-list" data-bind="template: {name: 'contactsTemplate', foreach:contacts}">
</ul>
and the following ModelView:
var contactViewModel = function (contacts) {
var self = this;
self.contacts = contacts;
self.test= function () {
console.log("CLICK");
}
if i use this code, the click event doesn’t fire. If i create a anonymous function like:
<script id="contactsTemplate" type="text/html">
<li data-bind="click: function(){contactViewModel.test()}">${DisplayName}</li>
</script>
i get the following exception:
Uncaught TypeError: Object function (contacts) {
var self = this;
self.contacts = contacts;
self.test= function () {
console.log("CLICK");
}
} has no method 'test'
SOLUTION
the solution is: $parent.
data-bind="click: $parent.test"
Your
contactViewModelfunction is a constructor function, however, you are trying to use it like an instance of an object that has been constructed via the function. YourcontactViewModelexposes an array of contacts which you are binding to thecontactsTemplatetemplate. For this reason, the ‘context’ of all bindings within this template are the object instances within your array. To bind to a function on the parent object, i.e. thecontactViewModel, use the Knockout 2.0 parent pseudo-variable: