简体   繁体   中英

Using 1 event handler for multiple templates

I have been using the usual Blaze Template.events way of handling events. Currently I have many events that are the same across multiple templates.

I was curious if anyone knew a way to handle events for multiple templates without having to use multiple Template.events calls for each different template.

(you could just write one event handler to apply to multiple templates).

If I switched to Meteor-React I think this could be done but I would rather not do that at the moment.

You can use this package called meteor-body-events

meteor add gwendall:body-events

Their git page is this: https://github.com/gwendall/meteor-body-events

I'd used it in my previous project and it works as expected, although, now I see that the project is no longer maintained. I believe it should still work as expected.

Example from their git page:

Template.body.events({
  "click .btn": function(e, data, tpl) {
    // e -> jquery event
    // data -> Blaze data context of the DOM element triggering the event handler
    // tpl -> the parent template instance for the target element
  }
})

So basically, you tag the event listener to the body once, and it will work for all templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM