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?

2
  • could you please share the relevant code? Commented Jan 8, 2018 at 11:45
  • Yes, I will edit it. Commented Jan 8, 2018 at 11:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
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 stackoverflow.com/questions/21638563/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.