Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly do a "bind" in angular2 typescript?

I want to use a javascript library that requires creating an object and binding to it like this:

this.mystr = "hello";
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = function(evt) {
    console.log(this.mystr); // this is undefined, even though I do have it defined
}

I would usually do a .bind(this)

Though in typescript I want to do this:

this.mystr = "hello"
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = onresult;

onresult(event) {    
    console.log(this.mystr) // this is undefined, even though I do have it defined
}

The .bind(this) does not work in this example. How do I get around this? Are there alternatives to just doing .bind(this)? Or whatever works for typescript functions?

like image 543
Rolando Avatar asked Jul 17 '17 05:07

Rolando


People also ask

How do you bind a function in TypeScript?

In JS, the first argument (within the bind() call) bind 'this' to the given object. But in TypeScript, functions created from function. bind are always preserve 'this'.

What does bind () method of?

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

What is bind () in JS?

JavaScript Function bind() With the bind() method, an object can borrow a method from another object. The example below creates 2 objects (person and member).

How do I bind HTML in angular 6?

Data Binding is available right from AngularJS, Angular 2,4 and is now available in Angular 6 as well. We use curly braces for data binding - {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser.


1 Answers

In TypeScript as well as in ES6 the most convenient way to bind a function is to use arrow function which preserves the context:

this.webkitspeech.onresult = ($event) => { this.onresult($event) };

Or use bind like this:

this.webkitspeech.onresult = this.onresult.bind(this);

Or you can use TS instance arrow function (ES class property) like this:

class MyClass() {
   onresult = ($event) => {...}
   ...
   this.webkitspeech.onresult = onresult;
}

Class properties is stage 2 ES7 proposal which is supported in TS today.

See the documentation for some comparison between the methods.

like image 151
Max Koretskyi Avatar answered Oct 05 '22 00:10

Max Koretskyi