Meteor.bindEnvironment(func, onException, _this)
3 तर्क स्वीकार करता है और यह जो फ़ंक्शन देता है वह तीसरे तर्क के लिए बाध्य है। इसे बनाए जाने के समय आपको इसे बांधना होगा और apply
या call
का उपयोग करके तर्कों को पास किया जाएगा, लेकिन this
संदर्भ पर ओवरराइड किया जाएगा।
function doSth() {
console.log(this.foo);
}
const fWithMeteorEnv = Meteor.bindEnvironment(doSth, null, {foo: 'foo'});
fWithMeteorEnv.call({foo: 'bar'}); // will print 'foo'
यह न कि जो आप Function.prototype.bind
साथ की उम्मीद करनी चाहिए के समान है। आपको call
एक बाध्य फ़ंक्शन की उम्मीद नहीं करनी चाहिए और इसके तर्क के लिए this
संदर्भ होना चाहिए।
let f = function() {
console.log(this);
}.bind({foo:'foo'});
f.call({foo: 'bar'}); // will log `{foo: 'foo'}`.
तुम सच में कुछ समारोह के लिए this
संदर्भ निर्धारित करने की जरूरत है, तो आप इसे लपेटो और यह आवरण कार्य करने के लिए एक पैरामीटर के रूप बजाय पारित कर सकते हैं (उदाहरण के लिए, के रूप में आवरण को पहला तर्क का उपयोग this
मूल फ़ंक्शन का संदर्भ)।
यदि आपको लौटाए गए फ़ंक्शन के call
अर्थशास्त्र दोनों की आवश्यकता है, तो यह को एक समेकित तरीके से किया जा सकता है।
/**
* Wraps the function.
* When the returned function is called, it sets the wrapped function's `this` to its first
* argument and passes it the rest of its arguments.
*/
function _wrapToMakeCallable(fn) {
return function() {
var _this = Array.prototype.shift.apply(arguments);
fn.apply(_this, arguments);
}
}
/**
* This function wraps the boundWithEnvironment function and maps the arguments such
* that it can be `call`ed or `apply`-ed as normal, using `wrapper`.
*/
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'}); // will print 'foo'
const callable = callableWrapAsync(doSth);
callable.call({foo:'bar'}); // will print 'bar'
});