5

We are working on a very large codebase. It's basically a web-based operating system, with its own file system and applications. The system's UIs are generated dynamically with Javascript.

We've decided to introduce Google Analytics to track various user activities.

Our concern is that in order to send data to Google Analytics servers on these events we'd have to scatter analytics code in all event handlers. Even if we wrap the analytics calls in a module, we'd still have to call it. E.g. usual code:

$(importButton).on('click', function() {
    // ... call import module to do import stuff
})

becomes, roughly speaking

$(importButton).on('click', function() {
    // ... call import module to do import stuff
    analytics.registerEvent('import')
})

And so the analytics code becomes extremely tightly coupled to the interface logic.

How do we introduce analytics in a modular fashion, without scattering analytics calls over all event handler functions?

gnat
  • 20,543
  • 29
  • 115
  • 306

1 Answers1

4

You don't have to change existing code, because you can just add more event handlers. JavaScript naturally supports multiple event handlers on a single element, and it's even easier with libs/frameworks like jQuery:

// in existing code:
$('#button').on('click', function (event) {
    console.log('normal behavior');
});

// somewhere else:
$('#button').on('click', function (event) {
    console.log('user tracking');
});

This does not affect performance significantly and you can always improve it with event delegation.

scriptin
  • 4,432