Binding 'this' from renderer to browser


#1

Hey all,

I am having a bit of trouble trying to handle this login error function. I am using the ipc module to send the login creds to the browser, then the browser will reply back to the renderer code with the ipc.sender.send(). So say I sent ‘error’ back to the renderer, I would handle it like:

ipc.on(‘login-reply’, function(arg){
if (arg === ‘error’) {
this.shake();
}
});

but the problem is, ‘this’ is no longer defined; therefore, I cannot call my shake method… how can I bind ‘this’ to the ipc send and back again from the browser code so that I can call my method? (ipc in renderer —> ipc listening in browser —> ipc in renderer) Any tips or ideas would be appreciated.

Thanks!


#2

As you noticed this is a special keyword inside each function and its context is different than that of a normal variable. Its value only depends on how you call the function, not how it was defined. There are several possible solutions to your problem.

Save this in another object that refers to it and reference that object instead. Common choices for variable names are self and that, but personally I find the latter slightly confusing.

var _this = this;
ipc.on('login-reply', function(arg) {
  if (arg === 'error') {
    _this.shake();
  }
});

Use bind, this does exactly what you are asking.

ipc.on('login-reply', (function(arg) {
  if (arg === 'error') {
    this.shake();
  }
}).bind(this));

I don’t think there is a particular reason to prefer one over the other, but if anyone has a strong preference (or a completely different solution) please chime in.

The same problem bit me in the ass when I just started using Javascript and then again later when I hadn’t used it for a while. I suspect many people have had similar experiences. :smile:


#3

Awesome the bind on the ipc.on worked! I really appreciate it man! I have used var that = this; all over the place in a marionette app but I guess I really didn’t understand it, this was really helpful.