1

Im using Framework7 and AngularJS. Lets say there is a page called: "something.js". In this page there is a socket.io method.

When loading the page once, the actions in the socket.io method will be fired only one time (which is correct).

When navigating to a different page and back to the page that runs the something.js file, the socket method will be fired twice and so for and so on.

somethine.js code:

socket.on("notification", function(notification) {
  // some code here
});

Now the only above code is loaded twice, so first time loading the something.js file, notification will be popped once. Next time, notification will be loaded twice, then three times.

How to tell socket.io to load the socket.on one time, or delete it when leaving the page or something?

Is it related to AngularJS views engine or to Framework7? How to avoid this?

Raz
  • 1,910
  • 1
  • 15
  • 28

1 Answers1

1

This happens because the subscription is not destroyed when the component is. In fact, you introduce by that a memory leak because your component cannot be collected by garbage collector until the event exists.

You have two options to fix that:

  1. Subscribe to the event in the service instead of the component and on the component's side inject the service and use the results
  2. Every time the component gets destroyed unsubscribe from the events manually, see How to unsubscribe from a socket.io subscription?

I personally prefer the first way because as long as you need to have a single subscription you need to use a singleton (service) to hold it.

smnbbrv
  • 23,502
  • 9
  • 78
  • 109
  • On the first way, what that you mean is to create a service in main app.js file then inject it as a dependency in the controller? But how the controller will know that a socket was fired? could you please provide some info about this? – Raz Jan 08 '18 at 12:12
  • I have found the way to solve this but putting the socket.on method in the main app.js file (which is loaded only once). Then fire a rootScope function located in the something.js file. It is working now. is it a good move? Thanks. – Raz Jan 08 '18 at 12:35
  • not really, because the dependency injection is not used, thus not really testable etc. Btw you can inject the rootScope in the service as well and emit the event from there. However, the rootScope events are kinda not performant, you may consider using pubsub instead https://stackoverflow.com/questions/21638563/angularjs-pubsub-vs-broadcast – smnbbrv Jan 08 '18 at 14:05