Using jQuery on () with objects in memory

I am going to write a jQuery plugin to handle Google Analytics tracking using html5 data attributes.

The code is very similar to the alpha stage, but the attached fiddle shows that it tracks individual dom elements and pushes Results to the right. (You will see all this on the console).

My only real concern is memory usage. I am currently binding individual event handlers to each element, and as we all know, this can become messy and intense.

Ideally, I would like to keep every tracker object in a central place and do some kind of search inside the jQuery on() function to trigger pushToGoogle() with the right context.

Unfortunately, my JavaScript cuts cannot completely fake it, and I cannot find an effective way to wrap everything in a neat, generic way.

Any ideas?

+4
source share
2 answers

It turns out that the process is actually quite simple and requires some refactoring.

I have added my code plugin to github so that someone following the question can learn from my sample code.

0
source

You can use event bubbles.

 $(document).on('click', 'a.trackEvent', function () { /* do complicated things */ }); 

Basically, any a.trackEvent element in a document (so that all your links with the trackEvent class) will function when clicked.

The advantage is only one function in memory, and if you dynamically create new dom elements, they will also be tracked. You just need the add code to identify the item.

It was a live feature: http://api.jquery.com/live/

0
source

Source: https://habr.com/ru/post/1383101/


All Articles