Code:nguyên cảo bối cảnh sai này
export class ViewModel {
public users: knockout.koObservableArrayBase;
constructor() {
this.users = ko.observableArray([]);
this.removeUser = this.removeUser.bind(this);//<-- Here compiller shows error
}
removeUser(user: User): void {
this.users.remove(user);
}
}
Html:
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody data-bind="foreach: users">
<tr>
<td><a href="#" data-bind="click: $root.removeUser">Remove</a></td>
<td data-bind="text: name"></td>
<td data-bind="text: surname"></td>
</tr>
</tbody>
</table>
Vấn đề là trong phương pháp removeUser. Theo mặc định, nếu tôi không ràng buộc ngữ cảnh, thì đối tượng == UserToDelete - không phải viewModel này. Nếu tôi thêm vào hàm tạo: this.removeUser = this.removeUser.bind(this); (manually enforce context)
thì ngữ cảnh là khi cần == viewmodel này, nhưng sau đó TypeScript than phiền cho "Không thể chuyển đổi hàm thành (người dùng: User) => void yêu cầu chữ ký cuộc gọi, nhưng Hàm thiếu một."
Nếu bạn không ngại HTML lộn xộn, đây là giải pháp thay thế: Remove –