dchacke / entangled-angular

Client side counterpart to Ruby gem "Entangled" for Angular
MIT License
2 stars 0 forks source link

channel subscription cleanup #3

Closed ffabreti closed 8 years ago

ffabreti commented 8 years ago

@dchacke Hi Dennis, In this code:

// To retrieve all messages from the server and
// subscribe to the collection's channel
Message.all(function(err, messages) {
  if (!err) {
    $scope.$apply(function() {
      $scope.messages = messages;
    });
  }
});

I have the callback executed everytime the collection changes on server. I think that's the meaning of a subscription: two way data binding. Great! Question is: Should I put this code in a singleton (factory) so that it's setup only once? Or is there any way to cleanup the "eventlistener" (socket.onmessage) ? I mean, if I call Message.all() everywhere I need the colection I will have a callback rain, won't I?

dchacke commented 8 years ago

Yes, be sure to only set this up once. You can see in https://github.com/dchacke/entangled/blob/development/spec/dummy/public/app/entangled/entangled.js#L314 that a socket is created whenever Message.all is invoked.

The fact that a new socket is created every time is suboptimal and needs to be addressed. I have thought about this and I think all of Entangled should actually only need one socket for everything. I just noted this requirement down in this commit.

dchacke commented 8 years ago

Also, just to be clear: Message.all should be invoked only once, but the callback you pass to it will be invoked every time the data changes. This is how it is intended and is fine, otherwise there would be no real time behavior between server and client. The callback itself does not create a new socket every time it is run, instead it uses the socket created by Message.all.