单击绑定到foreach中的父函数 [英] Click binding to parent function in foreach
本文介绍了单击绑定到foreach中的父函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下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>
和js代码:
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);
当我单击按钮时,将为每个联系人调用Foo.我不希望在单击任何链接之前都不会调用此函数.
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.
推荐答案
如 nemesv 所述.该参数是功能参考.因此,您正在做的就是将函数的结果用作click事件.
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>
这篇关于单击绑定到foreach中的父函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文