Suppose there is a scheme in SVG format, on which there are a lot of different elements, for each element you need to add a click event, how to ( efficiently ) add an event to hundreds of elements. Is it justified to use such a directive, or is it easier by means of jQuery

var app = angular.module('pl', []); app.controller('MainCtrl', function($scope) { }); app.directive('rect', function() { return function(scope, element, attrs) { element.bind("click", function(event) { console.log("clicks"); }); }; }) 
 <body ng-controller="MainCtrl"> <svg id="svgg" width="600px" height="600px"> <rect x="0" y="0" width="10px" height="10px"/><rect x="0" y="10" width="10px" height="10px"/><rect x="0" y="20" width="10px" height="10px"/><rect x="0" y="30" width="10px" height="10px"/> ... </svg> </body> </html> 

http://plnkr.co/edit/P97VaDMvyJ63xMxh4KjE?p=preview

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Due to performance considerations, I would recommend using the event delegate method. This method works quite simple:

  1. An event is bound to a parent in which many elements are located.
  2. event.target is checked in the event handler of this event, that is, it is checked who exactly caused this event ( rect tag). This is done in case the parent has other elements that do not need to be processed.
  3. Logic is running

This method reduces memory consumption, because one event of one element is listened to, and not 100 pieces.

This can be done either with native JavaScript or jQuery, or with AngularJS, only the directive needs to be added for the parent of the rect'ов , as an option to svg .