Worth it to create global function for code in onCreated?


I have several Templates that contain a search button to search for items on their pages.
The user can also trigger the search by hitting ‘enter’ on the keyboard. I achieve this by doing the following in each of the Template’s onCreated methods.


Template.foo.onCreated(function () {
    $(document).on('keyup', (e) => {
            if (e.keyCode === ENTER_CODE) {

I also remove the eventlistener in each template’s onDestroyed. My question is, is there any proper away to abstract what I have above so that I’m not repeating it per every Template that has search. I’m not sure if putting this into the global namespace as a function would even work because it’s affecting document.body. Would it even be worth abstracting this away or is it not really a big deal just given the nature of it (each template is independent)

Maybe you can create a component template and put all logic inside component. Your component can be a button.

1 Like