码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
问题出在removeUser方法中.默认情况下,如果我没有绑定上下文,这= = UserToDelete - 而不是viewModel对象.如果我添加到构造函数:this.removeUser = this.removeUser.bind(this); (manually enforce context)
,那么上下文就是这个== viewmodel,但是然后TypeScript抱怨"无法将函数转换为(user:User)=> void需要一个调用签名,但是Function缺少一个."
我经常有这样的对象:
var objectToMap = {
Id: 123,
UserType:{
Id: 456,
Name:"Some"
}
};
Run Code Online (Sandbox Code Playgroud)
当我需要在用户界面中修改此对象时,我想从某个列表中进行选择.例如,数组:
var list = [
{Id:456, Name: "Some"},
{Id:567, Name: "Some other name"}];
Run Code Online (Sandbox Code Playgroud)
我使用选项绑定,类似的东西:
<select data-bind="options: list, optionsText: 'Name', value: UserType, optionsCaption: 'Select...'"></select>
Run Code Online (Sandbox Code Playgroud)
问题是,淘汰赛认为来自objectToMap {Id:456,名称:"Some"}的UserType与列表中的对象{Id:456,名称:"Some"}不同.因此,自动UserType从列表中获取未定义但不需要的选项.
我通过这种方式克服了问题:我使用ko.utils.arrayFirst在列表中找到项目并替换objectToMap中的UserType.但这看起来很难看,需要额外的编码.有更好的方法吗?
我有简单的课程:
/// <reference path="..\typings\jquery\jquery.d.ts"/>
/// <reference path="..\typings\knockout\knockout.d.ts"/>
module Some.Namespace {
export class TestBase {
public field1: KnockoutObservable<string> = ko.observable("");
public onFieldChange: KnockoutComputed<string> = ko.computed(() => {
return this.field1();
}, this);
}
export class Test extends TestBase {
public field2: KnockoutObservable<string> = ko.observable("");
public onFieldChange() {
super.onFieldChange() + this.field2();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题,打字稿不允许在重写方法中使用关键字super.它说:
错误1类'Some.Namespace.Test'不能扩展类'Some.Namespace.TestBase':类'Some.Namespace.Test'定义实例成员函数'onFieldChange',但扩展类'Some.Namespace.TestBase'将其定义为实例成员属性.
错误2只能通过'super'关键字访问基类的公共方法.
如何覆盖knockout计算方法并且不松开基本方法?