我正在尝试使用TypeScript进行Knockout,并尝试将包含另一个模型的视图模型作为参数发送到以下函数:
打字稿:
export interface IEmployee {...}
export interface ICompany {...}
export class ViewModel() {
constructor(company : ICompany) {}
public setAsOwner(parent : ViewModel, person : IEmployee) {
parent.company.updateOwner(person.id);
}
}
// In a different file
ko.applyBindings(new ViewModel(new ICompany()));
HTML:
<ul data-bind="foreach: employees">
<li>
@*Employee details...*@
<button data-bind="click: $root.setAsOwner.bind($parent, $data)">
Set as new owner
</button>
</li>
</ul>
但是我不断收到错误消息,指出parent.company
未定义。将视图模型作为参数传递给自己的函数的正确方法是什么?
答案 0 :(得分:0)
click
绑定处理函数自动接收当前员工项作为第一个参数,如果从包装函数调用$parent.setAsOwner
,则父视图模型可通过{{1 }}
所以将this
方法更改为:
setAsOwner
和HTML to:
public setAsOwner(person : IEmployee) {
this.company.updateOwner(person.id);
}