phoenixframework/phoenix — pull request #457 by mgamini (2014-11-05 02:03:18+00:00)
Title: Adding onJoin callback to beat race condition on channel join

Optimally, a webapp utilizing a socket will go through the following flow when joining a Phoenix socket:

1. Webapp fires a join request
2. `phoenix.js` registers the request, submits the request to Phoenix, returns the channel in a callback
3. Webapp receives the channel, binds a "join" event
4. Phoenix server receives join request, responds with a join message (e.g. ` %{content: "joined #{topic} successfully"}`)
5. Webapp join event is triggered with the message

Unfortunately, especially when developing locally, step 4 occurs before step 3, resulting in a message sent to the webapp without a listener ready to handle it.

This small change to the way the Channel class is constructed adds a special onJoin callback immediately upon construction, which is also immune to being cleared on reset. This ensures that the Webapp will be ready to receive the join event from Phoenix, no matter how fast it is.