2013-09-04 22 views
5

私は以下のTypeScriptクラスを持っています。Typeクラス内のjquery関数スコープ内のメソッドを呼び出す

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は次のとおりです。私はこれを行うことができますTypeScriptドキュメントで見てきた

BrandViewModel.prototype.Get = function() { 
     $.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",() => function(items) { 
      $.each(items, function (i, item) { 
        this.Add(item.Id, item.Name, item.Active); 
       }); 
     }, "json"); 
    } 

_thisBrandViewModelインスタンスへの参照になりましたが、thisはjquery内にあります機能は、私が期待するかもしれないと_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に:

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

生成する:

+0

私のデモについて教えてください。なぜそれが実行できないのか分かりません。https://stackoverflow.com/questions/46834032/uncaught-typeerror-this-delete-is-not-a-function – ziqi

答えて

11

あなたがこれを行うことができます=>を使用している場合

ECMAScript 6 arrow functionsと一致
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"); 
    }; 
+0

非常にいいね、ありがとう。それがどのように機能するかについて少しの説明がありますか?すなわち、両方の機能の外側に「_」を配置することを知っているか? – Pricey

+1

太い矢印の表記法を使用すると生成されます。 ()=> { – basarat

+0

@basarat太い矢印の表記が2回使用されていてネストされていますが、どのように '_this'が正しい場所に置かれますか? – Pricey

0

を、活字体は、辞書的にこれをバインドします。

関連する問題