How to create a universal event across templates

Hi All,

I am looking to create an event helper, something like:

Template.sample_template_here.events({ "click .button": function(e,t){ //do something } })

But instead for just one template, it works across several templates, so I do not need to copy and paste code. is there a way to do this in meteor? I cannot seem to find the correct way

Thanks for any help you can provide

The events parameter is just a javascript object, so you could define this object anywhere you want, then re-use it as needed. For example, you could create a /imports/ui/common/events.js file, with something like:

const commonEvents = {
  'click .button'(e,t) {
    // Do something awesome!
  }
  ...
};

export default commonEvents;

then in your template’s:

import commonEvents from '/imports/ui/common/events.js';
import { _ } from 'meteor/underscore';
...
Template.sample_template_here.events(
  _.extend({
    'click .template-specific-event'() {
      // This event isn't shared
    }
    ...
  }, commonEvents); // Merge in the common events
);
...
2 Likes