Meteor.bindEnvironment(func, onException, _this)
takes 3 arguments, and the function returned by it is bound to the third argument. You need to bind it at the time of its creation, and using apply
or call
, it will pass arguments , but the this
link will be redefined .
function doSth() { console.log(this.foo); } const fWithMeteorEnv = Meteor.bindEnvironment(doSth, null, {foo: 'foo'}); fWithMeteorEnv.call({foo: 'bar'});
This is similar to what you would expect with Function.prototype.bind
. You should not expect a call
related function and have your this
context as an argument.
let f = function() { console.log(this); }.bind({foo:'foo'}); f.call({foo: 'bar'});
If you really need to set the this
context for a function, you can wrap it and pass it as a parameter to the wrapper function (for example, use the first argument in the shell as the context for this
source function).
If you need the call
semantics of the return function, this can be quite confusing.
function _wrapToMakeCallable(fn) { return function() { var _this = Array.prototype.shift.apply(arguments); fn.apply(_this, arguments); } } function callableWrapAsync(fn) { const bound = Meteor.bindEnvironment(_wrapToMakeCallable(fn)); return function() { Array.prototype.splice.call(arguments, 0, 0, this); bound.apply(this, arguments); } } function doSth() { console.log(this.foo); } Meteor.startup(function() { const fWithMeteorEnv = Meteor.bindEnvironment(doSth, null, {foo: 'foo'}); fWithMeteorEnv.call({foo:'bar'});
source share