Fred J. Fred J. - 3 months ago 13
Javascript Question

Template event selector 'not' isn't working

In this Meteor template code, when the

canvas
is clicked, it prints out the
canvas
element to the console but it is expected not to fire the event.

How can it be made so that it fires if the element which is clicked is not a
canvas
?

Template.myTemp.events({
'click *:not(canvas)': function(e) {
e.stopPropagation();
console.log(e.target);
});


enter image description here

Answer

Definitely an interesting problem as the :not selector is supported by Blaze, and works properly with other HTML elements. You might want to open an issue about this in the Blaze repo.

The above being said, there are a few different ways you can work around this. You could add a check in your event handler to make sure you don't do anything with canvas related events:

Template.myTemp.events({
  'click *'(event, instance) {
    if (event.target.nodeName.toLowerCase() !== 'canvas') {
      // Handle non-canvas events ...
    }
  },
});

Another option involves chaining your event handlers, if you want to be able to filter out canvas events specifically. For example:

Template.myTemp.events({
  'click canvas'(event, instance) {
    event.stopImmediatePropagation();
    // Handle canvas click events only ...
  },
  'click *'(event, instance) {
    // Handle all click events except canvas click events, since they're 
    // captured and handled above ...
  },
});