1

I am connecting Angular JS application having multiple states(Routes) with Node server(Socket) running on back-end. When I visit some other state and come back to the state where socket code is written, it again gets registered and when an event fire, multiple times the function gets called, which affects the performance.

 var socket = io.connect('127.0.0.1:3000');

        socket.on("connect",function(){
          console.log("connected");
        });


          socket.on("test-channel:App\\Events\\NewMessage", function(message) {
              if (vm.questions.length < 3) {

                  console.log("question fetching started");
                  vm.fetch_q();

              }
          });

I tried by putting the io.connect('localhost') in service also and put only the event in controller, but then also it is getting fired multiple times.

Honey Thakuria
  • 223
  • 3
  • 16
  • What is your question? every time you load the controller - the code inside is running, including`var socket = io.connect('127.0.0.1:3000');` command, so its try to connect to the server again. move the connection code to separate service and use the service all over your app. – Elad Dec 05 '17 at 22:08
  • I tried putting var socket = io.connect('127.0.0.1:3000'); into a service also, and put the socket.on('event',function(){}) event inside the controller, but then also it is getting called multiple times. The problem is that, socket.on("connect",function(){ alert("connected"); }); events get fired every time I revisit the page – Honey Thakuria Dec 06 '17 at 06:43

1 Answers1

0

The problem is that your controller set the 'on' event every time when you access that controller and it doesn't remove it only on refresh.

If you use AngularJS you can simply declare $rootScope.socket = io.connect('127.0.0.1:3000'); then use it in your controllers like this $rootScope.socket.emit('event', {}); , same method when you want to listen an event but use on insted of emit.

Anyway, this is a method that increase the performance and the way that you develop the program but the problem from your question is still there because isn't very good to keep your event listeners in your controllers -- only if you emit something.

You can solve the problem using the event listeners in AngularJS Run service.

app.run(function($rootScope){
  $rootScope.socket.on('event', function(){
    // Do something..
  });
}

And if you have more events to listen for you can declare the event in a module then require the module in run service. Hope to be a good solution for you.

Stepan Rafael
  • 365
  • 2
  • 4
  • 13