简体   繁体   中英

calling function in onopen event of websocket in React.js component

I am using websocket in React.js component, and trying to call a local method register in onopen event of websocket. console.log() is working ok inside onopen event, but my local function register is not. I am getting errror register is not a function .

Here is the code

this.ws.onopen = function()
{
  console.log('Connected! now registering');
  this.register();
}

Any help!

That's because the value of this is changing. What's happening is you're assigning a function to this.ws.onopen , and then the web socket instance is invoking onopen where this points to the web socket itself, and not your reactjs class instance. You need to preserve a reference to your reactjs class instance and use that to invoke the register method:

this.ws.onopen = () =>
{
  console.log('Connected! now registering');
  this.register();
}

The above uses arrow functions (an ECMA6 feature) to preserve the value of this. This works because arrow functions don't allow their caller (in this case the web socket) to change their value of this . Or you can do:

var self = this;
this.ws.onopen = function()
{
  console.log('Connected! now registering');
  self.register();
}

which simply stores a reference to your reactjs object prior to executing the function where the value for this gets changed. Or you can do:

this.ws.onopen = function()
{
  console.log('Connected! now registering');
  this.register();
}.bind(this)

which, prior to assigning a function to the property this.ws.onopen asserts that no matter who or how the function is called, the value of this for the function will always be whatever you passed to .bind .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM