In Meteor how can I create a generic event handler?

You can bind a high-level template to elements created with child templates. Then you only have to do the binding once. For example

HTML:

<template name="settings">
    {{> login_settings }}
    {{> account_settings }}
    {{> data_settings }}
</template>

<template name="login_settings">
  <btn class="slideToggle">Slide me for login!</btn>
</template>

<template name="account_settings">
  <btn class="slideToggle">Slide me for account!</btn>
</template>

<template name="data_settings">
  <btn class="slideToggle">Slide me for data!</btn>
</template>

JavaScript:

Template.settings.events {
  'click .slideToggle': function() {
    var clickedElement = event.target;
    // add/remove CSS classes to clicked element
  }
};

So if you end up creating 10 different template definitions under settings so you still only have to bind the handler to a single template.


I feel like you're overcomplicating things. Why not do this?

Template.someTemplate.events({
  'click .button': buttonClicked
});

function buttonClicked(evt) {
  // DRY code to handle a button being clicked
}

This has the right balance of separation: your event handler is defined once, but you can tell each template that you want its buttons to listen to some event. And if that's not good enough, you can further abstract it:

Template.someTemplate.events(genericEvents);

And possibly even merge genericEvents with specific events for that Template if you wanted.