单击处理程序中的Typescript和错误类型
我的打字稿单击处理程序中的Typescript和错误类型,typescript,knockout-3.0,Typescript,Knockout 3.0,我的打字稿 export class CustomerUIModel implements CustomerIntrerfaces.ICustomerUI { public customers: KnockoutObservableArray<CustomerIntrerfaces.ICustomer>; service: CustomerIntrerfaces.ICustomerService; constructor(svc: CustomerIn
export class CustomerUIModel implements CustomerIntrerfaces.ICustomerUI {
public customers: KnockoutObservableArray<CustomerIntrerfaces.ICustomer>;
service: CustomerIntrerfaces.ICustomerService;
constructor(svc: CustomerIntrerfaces.ICustomerService, data: CustomerIntrerfaces.ICustomer[]) {
this.service = svc;
this.customers = ko.observableArray(data);
}
public AddCustomer(elem: CustomerIntrerfaces.ICustomer): void {
this.service.Insert(elem)
.then(cRes => {
this.customers.push(elem);
})
.catch(r => {
alert(r.message);
});
}
}}
导出类CustomerUIModel实现CustomerInterfaces.ICCustomerUI{
公众客户:淘汰赛;
服务:CustomerIntrerfaces.iccustomerservice;
构造函数(svc:CustomerIntrerfaces.iccustomerservice,数据:CustomerIntrerfaces.iccustomer[])){
该服务=svc;
this.customers=ko.observearray(数据);
}
public AddCustomer(元素:CustomerIntrerfaces.iccustomer):无效{
this.service.Insert(elem)
。然后(cRes=>{
这个.客户.推送(elem);
})
.catch(r=>{
警报(r.message);
});
}
}}
我的HTML:
<tbody data-bind="foreach: customers">
<tr>
<td><input type="text" class="form-control" size="5" data-bind="value: CustomerID" /></td>
<td><input type="text" class="form-control" data-bind="value: CompanyName" /></td>
<td><input type="text" class="form-control" data-bind="value: ContactName" /></td>
<td><input type="text" class="form-control" data-bind="value: Country" /></td>
<td>
<input type="button" class="form-control" value="Insert" data-bind='click: $root.AddCustomer' />
<input type="button" class="form-control" value="Delete" data-bind='click: $root.DeleteCustomer' />
</td>
</tr>
</tbody>
当我点击“插入”时,我进入AddCustomer(),但this.service和customers一样为空。此外,“this”有一个CustomerIntrerfaces.iccustomer,而不是我所期望的CustomerIntrerfaces.iccustomer服务。如何修复此问题?看起来Knockout没有使用所需的
this
上下文调用AddCustomer
方法。看见您可以通过如下方式绑定方法,强制将this
上下文作为CustomerUIModel
对象:
public AddCustomer = (elem: CustomerIntrerfaces.ICustomer): void => {
this.service.Insert(elem)
.then(cRes => {
this.customers.push(elem);
})
.catch(r => {
alert(r.message);
});
}
有关一般问题的更多信息,请参阅。我不理解您对
=>
表示法的反对意见,但我链接的线程中还有一些其他选项。