Questions on `Meteor.bindEnvironment`


#1

I am a bit confused about the behavior of bind with Meteor.bindEnvironment, as well as the scoping of this with Meteor.bindEnvironment. For example, with arrow functions, arrow functions should maintain the outer scope:

Essentially it allows you to create an anonymous function with the contextual value of “this” being the scope of the function being that of the outer function that the arrow function is being defined in.
So, when I use the following code, it appears to work, but the console.log seems to say this is the scope of Meteor.

Cylon = new EventEmitter();
Cylon.messages = new Mongo.Collection('_cylon_messages');
Cylon._commands = net.connect(Settings.connection);
Cylon._createConnection = function (name, connection) {
  let socket = net.connect(connection, Meteor.bindEnvironment(() => {
    this.messages.insert({ name: name, message: 'connected'})
  }));
  socket._name = name;
  return socket;
}

Another example I’ve been having trouble understanding is using bind in callbacks that require Meteor.bindEnvironment. For example:

Cylon.execute = function (routine) {
  check(command, String);
  let future = new Future();
  let done = future.resolver();
  this.once('End', Meteor.bindEnvironment(done.bind(null, routine)));
  this._commands.write(`XQ#${routine}\r`, 'utf8');
  future.wait();
  this.removeListener('End', Meteor.bindEnvironment(done.bind(null, routine)));
  return future;
}

How does Meteor.bindEnvironment work with bindings of this to a function? Is there a proper usage?


#2

source


#3

I think meteor saves things like connectionId, userId in that method and assigns those saved values when your function runs so that you can get the right userId with Meteor.userId. It shouldn’t have anything to do with this variable and lexical scope.