2

我是 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)部件。我只看到了根本不需要参数的示例。

4

1 回答 1

3

箭头/lambda 语法如下所示:

class ClassName {
   model: any;

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

如果您有多个参数,请使用以下格式:

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

希望这可以帮助,

于 2014-01-17T21:56:20.420 回答