0

I am unable to understand this piece of JavaScript:

  Template.welcome.events({
    'submit form' (event, template) {
      event.preventDefault()
    }
  })

Is submit form the name of a method, with a space in it? If that's the case is the opening curly brace on line 1 denoting the start of a block scope?

Is this just a typo in the code and there's supposed to be a : after 'submit form'?

I tried to put it through a linter and JSLint failed, but ESLint gave me unrelated errors about Template being undefined.

I found it on this example repository: https://github.com/themeteorchef/holiday-wish-list/blob/master/code/client/templates/public/welcome.js#L8..L12

Aditya M P
  • 5,127
  • 7
  • 41
  • 72

2 Answers2

2

This is an ES6 shorthand for defining methods in object literals.

It is equivalent and compiles to:

Template.welcome.events({
  'submit form': function (event, template) {
    event.preventDefault();
  }
});
MasterAM
  • 16,283
  • 6
  • 45
  • 66
  • Ah, thanks! Yeah I searched after your answer and found this: https://babeljs.io/docs/learn-es2015/#enhanced-object-literals – Aditya M P Nov 25 '15 at 18:11
2

This code sample is using ES2015 syntax, and can be rewritten using the standard ES5 syntax as follow :

Template.welcome.events({
  'submit form': function(event, template) {
    event.preventDefault();
  },
});

In ES2015, you can declare object methods using a simpler syntax that avoids the more verbose syntax specifying them as properties being functions. (property: function(){...}).

const object = {
  method1() {
    //
  },
  method2() {
    //
  },
};
saimeunt
  • 22,666
  • 2
  • 56
  • 61