diff --git a/src/directives/init.js b/src/directives/init.js index 01dcfc3..fcc3f13 100644 --- a/src/directives/init.js +++ b/src/directives/init.js @@ -7,7 +7,7 @@ angular.module('flow.init', ['flow.provider']) // use existing flow object or create a new one var flow = $scope.$eval($attrs.flowObject) || flowFactory.create(options); - flow.on('catchAll', function (eventName) { + var catchAllHandler = function(eventName){ var args = Array.prototype.slice.call(arguments); args.shift(); var event = $scope.$broadcast.apply($scope, ['flow::' + eventName, flow].concat(args)); @@ -19,9 +19,15 @@ angular.module('flow.init', ['flow.provider']) if (event.defaultPrevented) { return false; } + }; + + flow.on('catchAll', catchAllHandler); + $scope.$on('$destroy', function(){ + flow.off('catchAll', catchAllHandler); }); $scope.$flow = flow; + if ($attrs.hasOwnProperty('flowName')) { $parse($attrs.flowName).assign($scope, flow); $scope.$on('$destroy', function () { diff --git a/test/init.spec.js b/test/init.spec.js index 243cd79..a065a34 100644 --- a/test/init.spec.js +++ b/test/init.spec.js @@ -66,6 +66,26 @@ describe('init', function() { expect(flowFactory.create).not.toHaveBeenCalled(); expect($rootScope.existingFlow).toBe(elementScope.$flow); }); + it('should remove event handlers from flow when the scope is destroyed', function () { + $rootScope.existingFlow = flowFactory.create(); + element = $compile('
')($rootScope); + elementScope = element.scope(); + + $compile('')($rootScope); + $rootScope.$digest(); + + var scopePrototype = Object.getPrototypeOf(elementScope); + spyOn(scopePrototype, '$broadcast').andCallThrough(); + $rootScope.existingFlow.fire('fileProgress', 'file'); + expect(elementScope.$broadcast.callCount).toEqual(2); + + elementScope.$destroy(); + scopePrototype.$broadcast.reset(); + + $rootScope.existingFlow.fire('fileProgress', 'file'); + expect(elementScope.$broadcast.callCount).toEqual(1); + + }); }); }); \ No newline at end of file