我的目标是创建一个TypeScript类并将其绑定为我的Knockout模型。一切正常,但是从数组中呈现的删除。当我在函数中查看调试器时,这个值的值不是被调用的方法的类,它是传递给方法的$ data的值。我需要进行哪些更改,以便将子元素传递给父元素并将其从数组中删除?我已经读过关于在孩子身上引用父母的内容,但我希望有更好的方法。提前谢谢。
<div class="box-head">
<h2 class="left">Tags</h2>
</div>
<div class="box-content">
<input type="text" placeholder="Add New Tag" data-bind="value: newTag, valueUpdate: 'afterkeydown'"/>
<button data-bind="click: AddTag">+Add</button>
<ul data-bind ="foreach: tags">
<li class="tagItem">
<span data-bind="text: name"></span>
<div>
<a href="#" class="tag-edit">Edit</a>
<a href="#" class="tag-delete" data-bind="click: $parent.RemoveTag">Delete</a>
</div>
</li>
</ul>
</div>
</div>
class Tag {
constructor(public id: number, public name: string) { }
}
class TagManager {
private data = [
new Tag(1, "Ball Handling"),
new Tag(2, "Passing"),
new Tag(3, "Shooting"),
new Tag(4, "Rebounding"),
new Tag(4, "Dribbling"),
];
tags: KnockoutObservableArray<Tag>;
newTag: KnockoutObservable<string>;
constructor() {
this.tags = ko.observableArray(this.data);
this.newTag = ko.observable("");
}
AddTag(): void {
if (this.newTag() !== "") {
this.tags.push(new Tag(this.tags().length + 1, this.newTag()));
this.newTag("");
}
}
RemoveTag(tag: Tag): void {
//I can't call this.tags here because 'this' referes to tag
var removed = this.tags.remove(tag);
}
}
$(function () {
var tagManager = new TagManager();
ko.applyBindings(tagManager);
});
答案 0 :(得分:2)
使用箭头功能,因此打字稿可以捕获&#34;这个&#34;实例
RemoveTag = (tag: Tag) : void => { this.tags.remove(tag; }