Skip to content

Commit

Permalink
Update init to remove event listeners on scope.$destroy
Browse files Browse the repository at this point in the history
  • Loading branch information
twilczak committed Feb 21, 2015
1 parent 70d57e7 commit 1b2bc83
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/directives/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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 () {
Expand Down
20 changes: 20 additions & 0 deletions test/init.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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('<div flow-init flow-object="existingFlow"></div>')($rootScope);
elementScope = element.scope();

$compile('<div flow-init flow-object="existingFlow"></div>')($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);

});
});
});

0 comments on commit 1b2bc83

Please sign in to comment.