Kaffee Bohne
Kaffee Bohne

Reputation: 1477

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 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"

Upvotes: 3

Views: 3372

Answers (1)

ColinE
ColinE

Reputation: 70142

Your contactViewModel function is a constructor function, however, you are trying to use it like an instance of an object that has been constructed via the function. Your contactViewModel exposes an array of contacts which you are binding to the contactsTemplate template. 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. the contactViewModel, use the Knockout 2.0 parent pseudo-variable:

data-bind="click: $parent.test"

Upvotes: 3

Related Questions