Typoskript aufrufen von Methoden auf der Klasse in jquery-Funktion Bereich

Habe ich die unten Typoskript Klasse.

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");
        }
}

Den resultierenden javascript für die Get Methode ist:

    BrandViewModel.prototype.Get = function () {
        $.get("/api/brand", function (items) {
            $.each(items, function (i, item) {
                this.Add(item.Id, item.Name, item.Active);
            });
        }, "json");
    };

Habe ich gesehen in der TypeScript Dokumentation, dass ich dies tun kann:

    public Get() : void  {
        $.get("/api/brand", () => function(items) {
            $.each(items, function (i, item) {
                    this.Add(item.Id, item.Name, item.Active);
                });
        }, "json");
    }

Die Ergebnisse in die unten, wo _this ist jetzt eine Referenz auf das BrandViewModel Instanz, sondern die this innerhalb der jquery .each Funktion nicht geändert _this als ich erwarten könnte:

    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");
    };

Sondern ich habe getan, die unten 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");
    }

gibt mir die Ergebnisse, die ich wollte:

    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");
    };

Weiß jemand einen besser geeigneten Weg, dies zu tun?

InformationsquelleAutor Pricey | 2013-09-04
Schreibe einen Kommentar