AngularJS + Socket.io

AngularJS provides a very interactive user experience, just like Socket.io. When you combine them in a single page application awesomeness is squared.

But some of the AngularJS mechanics produce buggy behavior for Socket.io.

For example if you subscribe to an event in your controller and then go to another view scope this controller is destroyed, but event subscription is still stored in a global socket.io object. So when you go back and controller is reinstanciated you get a second subscription. After a while of you going back and forth there's a chaos!

You don't want to receive 2+ messages from 1 event in your let's say chat application. So how can we deal we it?

I'll let code and comments speak for itself (coffeescript):

And here's how you use it:

Some use case for using reconnect (it's so simple I should't have included it):

Popular posts from this blog

HTTP server in Ruby 3 - Fibers & Ractors

Next.js: restrict pages to authenticated users

Migration locks for TypeORM