Reputation: 1231
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!
Upvotes: 0
Views: 1717
Reputation: 13419
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
.
Upvotes: 2