Framework: Socket IO + Aurelia.IO double activation

Created on 4 Apr 2016  Â·  7Comments  Â·  Source: aurelia/framework

Guys , when its created a structure like this:

class Example{


emitAction(){
     socket.emit('testEmit', {id:id} );
     socket.on('response' ,(dtresp)=>{ alert('this alerts twice') } );
}

}

It triggers the "ON" response twice , but when i create it like this:

class Example{
   activate(){
   socket.on('response', (dtresp)=>{ alert('once') } );
}

emitAction(){
     socket.emit('testEmit', {id:id} );

}

}

It triggers once, but if i leave the model , and enters it again it will load twice.

question

Most helpful comment

If you subscribe in activate, you should unsubscribe in deactivate- here's an example:

class Example {
  handler =  dtresp => { 
    alert('once');
  };

  activate() {
    socket.on('response', this.handler);
  }

  deactivate() {
    socket.off('response', this.handler);
  }
}

This will prevent memory leaks and fix the issue you've described.

All 7 comments

I'm afraid I can't quite follow what you are talking about here. We will need more context.

@tallesdantas would you mind creating a gist.run or Plunkr example so we can help you debug this?

@tallesdantas, could it be caused by browsersync You might be using in development environment?

the problem is that if i put a socket listener inside the constructor of aurelia it will register as many times i enter in the model, it should only execute once.

You should register your listener’s in a separate service that is injected as a singleton to your topic V/VM
e.g. topic-listener.js constructor would contain all of your listeners.

On Apr 4, 2016, at 12:26 PM, tallesdantas [email protected] wrote:

the problem is that if i put a socket listener inside the constructor of aurelia it will register as many times i enter in the model, it should only execute once.

—
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub https://github.com/aurelia/framework/issues/388#issuecomment-205376472

If you subscribe in activate, you should unsubscribe in deactivate- here's an example:

class Example {
  handler =  dtresp => { 
    alert('once');
  };

  activate() {
    socket.on('response', this.handler);
  }

  deactivate() {
    socket.off('response', this.handler);
  }
}

This will prevent memory leaks and fix the issue you've described.

@jdanyow you saved my project i'm really thankfull dude, thanks alot =D

Was this page helpful?
0 / 5 - 0 ratings