filip
filip

Reputation: 1503

Click binding to parent function in foreach

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.

Upvotes: 11

Views: 18361

Answers (2)

Richard Dalton
Richard Dalton

Reputation: 35793

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/

Upvotes: 18

nemesv
nemesv

Reputation: 139758

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.

Upvotes: 10

Related Questions