سؤال

Within an angular controller I am attaching to a websocket service. When the controllers scope is destroyed I obviously want to remove the subscription.

Is it safe to pass the current scope to my service subscription function so it can auto remove on scope destroy? If I dont then each controller who attaches to a socket listener has to also remember to clean up.

Basically is it safe to pass current $scope to a service function or is there a better way of doing this?

هل كانت مفيدة؟

المحلول

I had similar need in my project. Below is the object returned in a AngularJS factory (which initializes WebSocket). The onmessage method automatically unsubscribes a callback if you pass in 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 JavaScript equivalence is below.

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); 
  }
};

نصائح أخرى

I would not pass the scope. Instead, I would explicitly, in your controller, hook up the unsubscribe.

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 having this done explicitly is not as magical, and easier to follow the logic. I think the service would be doing too much if it were to also unsubscribe. What if a controller wants to unsubscribe early?

However, if you do have a very specific use case that's used everywhere, it would be fine to pass the scope in. The amount of time the service needs the scope is very small, basically when the controller first executes so that the service can listen to the $destroy event.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top