ES6 Arrow function is changing the scope of this in Meteor.publish [duplicate]
Asked Answered
M

1

9

So I been started using ES6 in Meteor, but apparently if you try to use Meteor.publish syntax with an arrow function, this.userId is undefined, while if you use it with a regular function(){} this.userId works perfectly, Im assuming is a kind of transpiler process that assign a different this, to userId but is just a guess, does anyone knows what really is happening?

Meteor.startup(function() {
    Meteor.publish("Activities", function() { //with function
        console.log(this.userId); //TS8vTE3z56LLcaCb5
    });
});

Meteor.startup(function() {
    Meteor.publish("Activities", ()=> { //with arrow function
        console.log(this.userId); //undefined
    });
});
Motoring answered 10/10, 2015 at 17:29 Comment(4)
From MDN: "An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value.' developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Bronchus
@FelixKling how this is a duplicate question?Motoring
It exaplains how this in arrow functions works.Bronchus
@FelixKling arrow function is specific in the context of ES6, while I understand your point I think that answer is not broad enough to understand that concept from Meteor perspective, you should reevaluate your decision IMHO.Motoring
J
7

This isn't a transpilation error, it's a feature of arrow functions. The arrow function automatically sets the context of the function body to the contexts here it was created, in this case the callback to Meteor.publish. This prevents Meteor from rebinding the context of your listener function.

From the Meteor publish docs:

Inside the function, this is the publish handler object

If you want things to work properly you will need to use the "old-school" function syntax to allow Meteor to set the context properly.

Jerriejerrilee answered 10/10, 2015 at 17:36 Comment(3)
It's called "arrow function", not "fat-arrow function".Bronchus
You are Completely right :) although there is a strong colloquial weight behind fat-arrow. I will update! ThanksJerriejerrilee
"An arrow function expression (also known as fat arrow function)..." -MDNCheckup

© 2022 - 2024 — McMap. All rights reserved.