Ind*_*000 4 knockout.js typescript
从一起开始使用Typescript和KnockoutJS,我遇到了一个我无法推理的错误.HTML如下所示:
<div class="panel panel-body">
<div class="list-group" data-bind="foreach: Items()">
<a href="#" class="list-group-item"
data-bind="text:Name, click: $parent.SetCurrent">
</a>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
打字稿如下:
/// <reference path="knockout.d.ts"/>
/// <reference path="jquery.d.ts" />
module ViewModels {
export class ItemViewModel {
public Name: KnockoutObservable<string>;
constructor(name: string) {
this.Name = ko.observable(name);
}//constructor
}
export class MainViewModel {
public SelectedItem: KnockoutObservable<ItemViewModel>;
public Items: KnockoutComputed<Array<ItemViewModel>>;
constructor() {
this.SelectedItem = ko.observable<ItemViewModel>();
this.Items = ko.computed({
owner: this,
read: () => {
return this.get_items();
}
});
}
//TODO: replace this with knockout.mapping plugin transforms
private convert_from_model(items_model) {
var arr = new Array<ItemViewModel>();
var owner = this;
items_model.forEach(function (item) {
var d = new ItemViewModel(item.name);
arr.push(d);
});
return arr;
}
private get_items(): Array<ItemViewModel> {
var items = [{ "name": "AAAA" }, { "name": "BBBB" }, { "name": "CCCC" }, { "name": "DDDD" }];
var items_c = this.convert_from_model(items);
return items_c;
}
public SetCurrent(item: ItemViewModel) {
this.SelectedItem(item);
}
}
}
window.onload = () => {
ko.applyBindings(new ViewModels.MainViewModel());
};
Run Code Online (Sandbox Code Playgroud)
问题是在点击事件上设置当前项目.
public SetCurrent(item: ItemViewModel) {
this.SelectedItem(item);
}
Run Code Online (Sandbox Code Playgroud)
click事件正确调用SetCurrent,但'this'的类型为ItemViewModel,而不是MainViewModel.我错过了一些明显的东西吗
这是一个VS2013解决方案,可以解决所有问题.
谢谢
click: $parent.SetCurrent
Run Code Online (Sandbox Code Playgroud)
Knockout始终使用thisset设置为当前视图模型来调用事件处理程序.这个特殊的绑定意味着(对Knockout)" $parent.SetCurrent以当前视图模型调用为this".
最简单的解决方法是使用箭头功能始终保持正确this
// Change the definition of SetCurrent like so:
public SetCurrent = (item: ItemViewModel) => {
this.SelectedItem(item);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1555 次 |
| 最近记录: |