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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With