javascript - TypeScript calling methods on class inside jquery function scope -
i have below typescript class.
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"); } } the resulting javascript get method is:
brandviewmodel.prototype.get = function () { $.get("/api/brand", function (items) { $.each(items, function (i, item) { this.add(item.id, item.name, item.active); }); }, "json"); }; i have seen in typescript documentation can this:
public get() : void { $.get("/api/brand", () => function(items) { $.each(items, function (i, item) { this.add(item.id, item.name, item.active); }); }, "json"); } which results in below, _this reference brandviewmodel instance this inside jquery .each function not changed _this might expect:
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"); }; instead have done below in 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"); } which gives me result wanted:
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"); }; does know more appropriate way this?
you can this:
public get() : void { $.get("/api/brand", (items) => { $.each(items, (i, item) => { this.add(item.id, item.name, item.active); }); }, "json"); } which generates:
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"); };
Comments
Post a Comment