Do I need to remove event handlers by directives when $ destroy fire?

I have seen many examples of directives, including the AngularUI command , where they do not see any cleanup.

Here is an example from their ui-date directive, which creates a jQuery datepicker. (a source)

element.on('blur', function() { ... }); 

They placed the event handler on the element, but in no case did they disable the event. I would expect that there will be code, for example:

 var namespace = ".uiDate"; element.on('blur' + namespace, function() { ... }); element.on("$destroy" + namespace, function () { element.datepicker("destroy"); //Destroy datepicker widget element.off(namespace); //Unbind events from this namespace }); 

So this makes me wonder if there is something that I don’t understand. Isn't that what they do causes a memory leak in situations where the w / this directive element is created and destroyed over and over again?

What am I missing?

+7
jquery angularjs jquery-ui angularjs-directive angular-ui
source share
1 answer

Yes, ideally you should clear any event handlers that are bound to elements other than the element associated with the directive.

For example, if your directive has a window resizing function for changing a directive element, you will need to remove the window resize event when the directive is destroyed.

here is an example directive that I had to create, and you can see that I had to untie event handlers attached outside the scope of the directive:

 lrApp.directive('columnArrow',function($timeout){ return { restrict : 'A', scope : { active : '=columnArrow' }, link: function($scope, elem, attrs, controller) { $scope.$watch('active',function(){ $timeout(function(){ adjust(); },0); }); $(window).resize(adjust); elem.parents('.column-content').scroll(adjust); $scope.$on('$destroy', function () { elem.removeClass('hide'); elem.parents('.column-content').unbind('scroll',adjust); $(window).unbind('resize',adjust); }); function adjust(e) { if($scope.active) { var parentScroll = elem.parents('.column-content'); var parent = elem.parent(); var visible = inView(parentScroll[0],parent[0]); if(!visible) { elem.addClass('hide'); } else { elem.removeClass('hide'); } var offset = parent.offset(); var w = parent.outerWidth(); var h = (parent.outerHeight() / 2) - (elem.outerHeight() / 2); elem.css({'top':offset.top + h,'left':offset.left + (w + 5)}); } }; } } }); 
+6
source share

All Articles