5

我有以下 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实例的引用,但thisjquery 函数内部没有像我预期的那样.each更改为:_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");
    };

有谁知道更合适的方法来做到这一点?

4

2 回答 2

11

你可以这样做:

    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");
    };
于 2013-09-04T16:06:57.033 回答
0

ECMAScript 6 箭头函数一致,TypeScript 在使用 => 时会在词法上绑定 this。

于 2013-09-04T21:54:29.090 回答