Reputation: 4440
I am new to Typescript, and attempting to introduce it to some of my stuff, but I am having difficulty with some scope and arrow functions.
In javascript, my code looks like this ...
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
});
Alright, so this has two problems. When I go to do this in Typescript, I do it like this...
class ClassName {
model: any;
subscribe() {
this.model.Prototypes.bind("change", function(e){
// FIRST PROBLEM
this.model ....
});
}
}
Alright, so this works up until the labelled part. this.model
is no longer a reference to what I think it is, because it is in the context of the function, not the 'class'. So I did some digging and learned I should be using an arrow function
, because that will preserve the context.
The problem is, I cannot conceive of how to do an arrow function and still pass through the parameters I need, like the change
value for the bind event, or the function(e)
part. I have only seen examples that expect no parameters at all.
Upvotes: 2
Views: 3273
Reputation: 52410
The arrow/lambda syntax would look like this:
class ClassName {
model: any;
subscribe() {
this.model.Prototypes.bind("change", e => {
// FIRST PROBLEM
this.model ....
});
}
}
If you have more than one parameter, use this format:
(p1, p2, p3) => { ... }
Hope this helps,
Upvotes: 3