Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click binding to parent function in foreach

Tags:

knockout.js

I have the following html:

<div data-bind="foreach: Contacts">
   <a data-bind="click: $parent.Foo($data), text: Name">link</a>
</div>
<button data-bind="click: AddContacts">click</button>

and js code:

var viewModel = ko.mapping.fromJS({"Selected":null,"Contacts":[]});
viewModel.AddContacts = function(){
    this.Contacts([{"Name":"C1"},{"Name":"C2"}]);
}

viewModel.Foo = function (contact) {
    alert(contact.Name);
}

ko.applyBindings(viewModel);

When I click the button the Foo is called for each contact. I didn't expect this to be called at all until any of the link is clicked.

like image 417
filip Avatar asked Dec 10 '12 16:12

filip


2 Answers

As nemesv said. The parameter is a function reference. So what you were doing was using the result of the function as the click event.

The call to your function that you pass will automatically include the data for that item so you do not need to pass it manually:

<div data-bind="foreach: Contacts">
   <a data-bind="click: $parent.Foo, text: Name">link</a>
</div>

http://jsfiddle.net/4cUv9/

like image 166
Richard Dalton Avatar answered Oct 22 '22 17:10

Richard Dalton


The click binding's parameter is a function reference. So you need to wrap your call into an anonymous function:

<div data-bind="foreach: Contacts">
   <a data-bind="click: function() { $parent.Foo($data); }, text: Name">link</a>
</div>

So when you want to pass additional arguments into your click binding you need to wrap it to make a function. See also the samples in the click documentation

The <button data-bind="click: AddContacts"> expression is working because you directly referencing the AddContacts function there.

like image 41
nemesv Avatar answered Oct 22 '22 15:10

nemesv