In my component I have a static need
property that stores a function
. Behind the scenes there is middleware that executes this function
in order to perform some asynchronous API calls before rendering the component. This is how it looks:
static need = [
myFunc(token)
]
However this causes issues, as having a token
parameter there actually executes the function, hence its promise is passed as need
, instead of function
itself. For example, this works perfectly fine, as it doesn't execute the function:
static need = [
myFunc
]
But this way I have no ability to pass a token. I'm trying to figure out how to pass this function to need
with a token, but without executing it, as it is done in middleware.
you can do
var need = [
myFunc, token
];
you can invoke it as
need[0].apply(null, need.slice(1-need.length));
Example DEMO
function a(b){ console.log(b) } var need = [ a, "1" ]; need[0].apply(null, need.slice(1-need.length));
Given that you have control of myFunc
:
function myFunc(params) {
return function() {
// do something with params
}
}
So in order to execute actual function code, you'll have to call it twice: myFunc('foo')()
, which suits your need to maintain parameters before calling a function.
You could use a closure
static need = [
function (token) {
return myFunc;
}(token);
]
ES6
static need = [
(token => myFunc)(token)
]
Probably by now you have resolve the issue but I feel instead of storing it in an array you can create an object & add this as an object property.There is no harm in storing it in an array
//Define the function
var need = {
myFunc:function(token){
alert(token)
}
};
// Invoking
need['myFunc'](1);
//dynamic invoke
var dynamicInvoke = 'myFunc';
need[dynamicInvoke](2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.