Safe transfer of the current $ volume from the controller control function to the corner

In an angular controller, I connect to the websocket service. When the controller area is destroyed, I obviously want to delete the subscription.

Is it safe to transfer the current area to my service subscription function so that it can be automatically deleted from the destruction area? If I don’t, then every controller that connects to the socket listener should also remember the cleanup.

In principle, is it safe to pass the current $ scope to a maintenance function, or is there a better way to do this?

+4
source share
2 answers

I had the same need for my project. The following is the object returned by the AngularJS factory (which initializes the WebSocket). The onmessage method automatically unsubscribes the callback if you pass its associated scope in the second argument.

 io = onmessage: (callback, scope) -> listeners.push callback if scope then scope.$on "$destroy", => @offmessage callback offmessage: (callback) -> listeners.remove callback 

The following is the equivalence of JavaScript.

 var io = { onmessage: function(callback, scope) { var _this = this; listeners.push(callback); if (scope) { scope.$on("$destroy", function() { _this.offmessage(callback); }); } }, offmessage: function(callback) { listeners.remove(callback); } }; 
+4
source

I could not get through. Instead, I would directly enable unsubscription directly in the controller.

From http://odetocode.com/blogs/scott/archive/2013/07/16/angularjs-listening-for-destroy.aspx :

 $scope.$on("$destroy", function() { if (timer) { $timeout.cancel(timer); } }); 

I think this is clearly not done as magical, and it is easier to follow the logic. I think that the service will be too much if he also unsubscribed. What if the controller wants to unsubscribe earlier?

However, if you have a very specific use case that is used everywhere, it would be nice to pass the scope. The amount of time a service needs an area is very small, basically when the controller first does this, the service can listen for the $ destroy event.

+2
source

Source: https://habr.com/ru/post/1496845/


All Articles