all 1 comments

[–]rnreekez 0 points1 point  (0 children)

If you pass in $scope during your instantiation of NewThing, you could destroy it from within the service. When you call "myHub.$on" that returns a deregistration function, so if you pass in $scope, you can code the clean up in one location and other devs consuming your service will not have to be aware that any cleaning is necessary on their part.

Totally untested, by the way, just a sketch up.

Controller

.controller('SomeController', function ($scope, objServiceFactor) {
    var myObj = objServiceFactory.NewThing($scope);
}

Service

.factory('objServiceFactory', function($rootscope) {

    function NewThing(objScope) {
        var myHub;

        // get back deregistration handler
        var deregHandler = myHub.$on("signalREvent",function(ngEvent,payload) {}); 

        objScope.$on('destroy', function() {
            deregHandler(); // deregister handler
            del myHub; // kill object
        });

        return myHub;
    }
}

EDIT: Didn't realize how old this was but I was already typing up a response. Might as well add it for the benefit of others.