2013-09-25 22 views
0

當我在ajax.error結果中調用this.getInvoices時,出現錯誤Uncaught TypeError: Object #<Object> has no method 'getInvoices' 。我如何從那裏訪問打字稿功能?Javascript函數中的調用手稿函數

// Typescript 
class InvoicesController { 
    ... 

    public getInvoices(skip: number, take: number): void { 
     ...  
    } 

    public createInvoice() { 
      $.ajax({ 
      ... 
      contentType: 'application/json', 
      type: 'POST', 
      success: function (res) { 
       if (res.result === 'ok') { 
        this.getInvoices(0,100); // THIS DOES NOT WORK? 
       } 
      }, 
      error: function (err) { 
       this.getInvoices(0,100); // THIS DOES NOT WORK? 
      } 
     }); 
    } 
} 
+1

可能重複[$(this)裏面的AJAX成功不工作](http://stackoverflow.com/questions/6394812/this-inside-of-ajax-success-not-working) –

+0

沒有這個必須做的打字稿 – daniel

+1

不,它沒有。 TypeScript編譯爲JavaScript。將'context'參數傳遞給'$ .ajax()'。 –

回答

2

檢查您的範圍。我相信,當你調用這個你實際上指的是Ajax對象,而不是類InvoicesController

public createInvoice() { 
     me = this; 
     $.ajax({ 
     .... 
     contentType: 'application/json', 
     type: 'POST', 
     success: function (res) { 
      if (res.result === 'ok') { 
       console.log('Data saved1'); 

      } 
      else { 
       console.log('Save error1'); 
      } 
     }, 
     error: function (err) { 
      me.getInvoices(100,0); // TRY THIS 

      console.log("error2"+err); 
     } 
    }); 
} 
+1

還有更好的解決方案:http://stackoverflow.com/a/6394826/139010 –

1

使用短打字稿功能語法,它在默認情況下擷類方面:

// Typescript 
class InvoicesController { 
... 

public getInvoices(skip: number, take: number): void { 
    ...  
} 

public createInvoice() { 
     $.ajax({ 
     ... 
     contentType: 'application/json', 
     type: 'POST', 
     success: (res) => { 
      if (res.result === 'ok') { 
       this.getInvoices(0,100); // WORK NOW 
      } 
     }, 
     error: (err) => { 
      this.getInvoices(0,100); // WORK NOW 
     } 
    }); 
} 

}