1

I have a problem with understanding ES6 arrow function syntax. Why this code does not work:

Meteor.publish('parties', (options, searchString) => {
...
}) 

But this one works:

Meteor.publish('parties', function (options, searchString) {
...
}) 
torayeff
  • 9,296
  • 19
  • 69
  • 103
  • 1
    Are you getting some kind of error? It looks syntactically fine. – TbWill4321 Dec 18 '15 at 16:22
  • @TbWill4321 no error. Just does not work. – torayeff Dec 18 '15 at 16:23
  • @TbWill4321 Receiving this error on server side Exception from sub parties id WHLG4KoSdkGm5RzcH TypeError: Object [object global] has no method 'added' – torayeff Dec 18 '15 at 16:25
  • 1
    You should read about what happens to the value of `this` when you use [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Saad Dec 18 '15 at 16:27
  • 1
    Ah. The perils of libraries that mess with the scope for the nicety of being able to refer to something library-related with the `this` keyword from your callback. IMO, this was never a good idea (jQuery, I'm looking at you) – spender Dec 18 '15 at 16:28
  • 1
    Again, how can someone learn about arrow functions without learning how `this` works inside arrow functions? – Felix Kling Dec 18 '15 at 16:49
  • @FelixKling For me and for those who wants to learn about this I'd recommend reading: https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/ and https://toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/ – torayeff Dec 18 '15 at 17:13

1 Answers1

4

The primary difference between example one and example two is that example one uses the calls scope while example two uses Meteors scope. If I had to make a guess it would be that it is not working because you are using this and expecting a different scope. Here is a quick example to demonstrate this functionality...

(function () {
    var Example = (function () {
        function Example() {
            setTimeout(function() {
                console.log(this); //this === window
            }, 0);

            setTimeout(() => {
                console.log(this); //this === test
            }, 0);
        }        
        return Example;
    }());

    var test = new Example();
}());

You can read about the specifics here

Marie
  • 2,114
  • 1
  • 17
  • 31