【发布时间】:2013-09-08 05:26:33
【问题描述】:
我有下面的 TypeScript 类。
export class BrandViewModel {
private _items = ko.observableArray();
public Add(id: number, name: string, active: boolean) : void {
this._items.push(new BrandItem(this, id, name, active));
}
public Get() : void {
$.get("/api/brand", function(items) {
$.each(items, function (i, item) {
this.Add(item.Id, item.Name, item.Active);
});
}, "json");
}
}
Get 方法生成的 javascript 是:
BrandViewModel.prototype.Get = function () {
$.get("/api/brand", function (items) {
$.each(items, function (i, item) {
this.Add(item.Id, item.Name, item.Active);
});
}, "json");
};
我在TypeScript 文档中看到我可以这样做:
public Get() : void {
$.get("/api/brand", () => function(items) {
$.each(items, function (i, item) {
this.Add(item.Id, item.Name, item.Active);
});
}, "json");
}
结果如下,其中_this 现在是对BrandViewModel 实例的引用,但jquery .each 函数中的this 没有像我预期的那样更改为_this:
BrandViewModel.prototype.Get = function () {
var _this = this;
$.get("/api/brand", function () {
return function (items) {
$.each(items, function (i, item) {
this.Add(item.Id, item.Name, item.Active);
});
};
}, "json");
};
相反,我在TypeScript 中完成了以下操作:
public Get(): void {
var _this = this;
$.get("/api/brand", function(items) {
$.each(items, function (i, item) {
_this.Add(item.Id, item.Name, item.Active);
});
}, "json");
}
这给了我想要的结果:
BrandViewModel.prototype.Get = function () {
var _this = this;
$.get("/api/brand", function (items) {
$.each(items, function (i, item) {
_this.Add(item.Id, item.Name, item.Active);
});
}, "json");
};
有人知道更合适的方法吗?
【问题讨论】:
-
你能帮我看看我的演示吗。我不知道为什么它不能运行stackoverflow.com/questions/46834032/…
标签: javascript jquery scope typescript