0

I'm trying to catch any click event inside the window from inside a template MyTemplate, with something like this:

Template.MyTemplate.events({
  'click' : function(e) {
    console.log("click");
    // Here I need to access Template.instance()
    // ...
  }
});

But the code above doesn't works as I would like but catches only clicks inside the template's DOM and I can't get clicks outside the template.

Also, I would like to have the code inside the template itself, so something like Template.body.events({ ... }) is not an option.


WHAT I TRIED

I already tried this solution:

function clickEvent(event) {
  console.log('click');
  // Here I can access the right `Template.instance()` as `this`
  // thanks to the bind below
  // ...
}

Template.MyTemplate.onCreated(function () {
  // The `bind` give me the template instance inside the `clickEvent`
  // function
  $(document).on('click', clickEvent.bind(this));
});

Template.MyTemplate.onDestroyed(function () {
  $(document).off('click', clickEvent);
});

It works but seems like a workaround: I have all events inside Template.MyTemplate.events({ ... }) while these ones are outside, I need to do a bind to get the template's instance and it uses JQuery to bind events and not Meteor itself.

So, is there no a simpler-way/Meteor-way to do that? Like some code that can go inside Template.MyTemplate.events({ ... })?

Community
  • 1
  • 1
Andrea
  • 15,900
  • 18
  • 65
  • 84
  • I think there is still some bugginess when binding to body from meteor, does this help? https://github.com/gwendall/meteor-body-events – Scottux Dec 19 '15 at 16:21
  • I don't that's possible, nor do I think the solution you mention is a workaround. I think your desire to keep the events "inside" the template is a little ill-guided. The event clearly is *not* inside the template, otherwise it would be caught, so you are merely trying to keep your code clean and retain the data context (which `bind` accomplished). – Christian Fritz Dec 19 '15 at 21:50
  • what about just wrapping your whole page in a template and attaching events to that? – Michel Floyd Dec 20 '15 at 02:08

0 Answers0