在jquery函数范围内的类上的TypeScript调用方法
我有下面的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"); };
有谁知道更合适的方法吗?
你可以这样做:
public Get() : void { $.get("/api/brand", (items) => { $.each(items, (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"); };
与ECMAScript 6箭头函数一致,当使用=>时,TypeScript会以词法方式绑定它。