0

I'm developing using mostly Chrome. I just discovered a bug, where the following snippet was working fine in Chrome, but not in Firefox.

Template.myTemplate.events({
  "click input[type=checkbox]"(){
    let context = event.target.dataset.context;
    InspireTheWorldWith.call({context});
  }
});

I could not quite believe my eyes, but essentially the variable 'event' was never assigned in the parameters of the event function. Yet this worked in Chrome without any issues. For the record, it clearly should be:

Template.myTemplate.events({
  "click input[type=checkbox]"(event, template){
    let context = event.target.dataset.context;
    InspireTheWorldWith.call({context});
  }
});

I'd like to read up more about this to really understand what is going on, but I'm struggling to find the approrpate 'keyword' to google. for.

Any suggestions?

For the record, I'm using Meteor 1.4, babel-runtime@6.18

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Hans
  • 2,800
  • 3
  • 28
  • 40
  • Can you add an ```event.preventDefault()``` and then see if it works fine? I've run into trouble with events where things work out of the box with chrome but not with other browsers. And event.PreventDefault() seems to make it work on other browsers. – blueren Nov 29 '16 at 16:55
  • The original code does a fair bit more, including event.preventDefault. But it had no impact on the actual behaviour with the omitted event variable. – Hans Nov 30 '16 at 00:11

1 Answers1

4

It's nothing to do with Meteor, just Chrome: Chrome does this to support code written originally for Internet Explorer; in addition to passing the event to the handler, it also sets it as a global event variable.

Microsoft's "new" event handling in IE5 (or was it 5.5?) used a global event object and attachEvent/removeEvent. Then DOM2 came along (after IE6 had been released) and defined addEventListener/removeEventListener where the event handler recieves the event as an argument. Then years passed before Microsoft supported DOM2 (in IE9).

So when Chrome was coming up, they made the decision to provide a global event object to increase compatibility with IE-specific code. Mozilla chose not to originally, but does now; more in my answer here.

You can see it here — run this on Chrome:

document.getElementById("target").addEventListener("click", function(e) {
  console.log("e === event? ", e === event);
}, false);
<div id="target">Click me</div>

As you can see, the global event object and the event object the handler receives are the same object.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875