2014-01-17 59 views
2

我是Typescript的新手,嘗試將它引入到我的某些內容中,但我在使用某些範圍和箭頭函數時遇到了困難。Typescript - 帶參數的箭頭函數

在JavaScript中,我的代碼看起來像這樣...

var model = params.model; 

model.Prototypes.bind('change', function(e){ 
    // some code to execute when the event occurs 
    model.set([some values]); // this performs an operation to the actual top level model 
}); 

好了,所以這有兩個問題。當我在Typescript中這樣做時,我這樣做...

class ClassName { 
    model: any; 

    subscribe() { 
     this.model.Prototypes.bind("change", function(e){ 
     // FIRST PROBLEM 
     this.model .... 
     }); 
    } 
} 

好的,所以這個工作起來,直到標記的部分。 this.model不再是我認爲它的參考,因爲它是在功能的背景下,而不是'班'。所以我做了一些挖掘並瞭解到我應該使用arrow function,因爲這樣可以保留上下文。

問題是,我無法想象如何做一個箭頭功能,仍然通過我需要的參數,如change價值的綁定事件,或function(e)部分。我只看到完全沒有參數的例子。

回答

2

箭頭/ lambda語法是這樣的:

class ClassName { 
    model: any; 

    subscribe() { 
     this.model.Prototypes.bind("change", e => { 
     // FIRST PROBLEM 
     this.model .... 
     }); 
    } 
} 

如果你有一個以上的參數,請使用以下格式:

(p1, p2, p3) => { ... } 

希望這有助於