ES6 Arrow function zooms in on Meteor.publish

So, I started using ES6 in Meteor , but apparently if you try to use the Meteor.publish syntax with an arrow, this.userId is undefined, and if you use it with a regular function(){} this.userId works fine, I assume that this is a kind of transpiler process that assigns a different value to userId , but this is just an assumption, does anyone know what is actually 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 }); }); 
+7
javascript ecmascript-6 meteor meteor-publications
source share
1 answer

This is not a transpilation error, it is a function of the arrow functions. The arrow function automatically sets the context of the function body to the contexts here where it was created, in this case the Meteor.publish . This prevents the Meteor from rechecking the context of your listener function.

From Meteor publish documents :

Inside a function, this is a publication handler object

If you want everything to be correct, you will need to use the syntax of the "old school" function to allow the Meteor to set the context correctly.

+7
source share

All Articles