KnockoutJS - Click event on template
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 an anonymous function like:
<script id="contactsTemplate" type="text/html">
<li data-bind="click: function(){contactViewModel.test()}">${DisplayName}</li>
</script>
I am getting the following exception:
Uncaught TypeError: Object function (contacts) {
var self = this;
self.contacts = contacts;
self.test= function () {
console.log("CLICK");
}
} has no method 'test'
Decision
solution: $ parent.
data-bind="click: $parent.test"
source to share
Your function contactViewModel
is a constructor function, however you are trying to use it as an instance of an object that was constructed with the function. Yours contactViewModel
provides an array of contacts that you bind to the template contactsTemplate
. For this reason, the "context" of all bindings in this template is an instance of an object in your array. To bind to a function of the parent object, i.e. contactViewModel
, use the parent pseudo variable Knockout 2.0:
data-bind="click: $parent.test"
source to share