I need to feed a pipe() handler function a bunch of function names so it can execute them in order, waiting for completion of each as it goes. This is great when those functions don't need parameters passing, but when parameters are needed I can't figure out how to pass them without the function going ahead and invoking itself (caused by the brackets).
For example, this is what I typically pass:
pipeHandler([function1, function2]);
It'll then invoke function1() and function2() before the promise is completed.
Where it gets difficult is when I want to do something like thiss:
pipeHandler([function1('value'), function2]);
That causes function1() to invoke immediately, completely bypassing the promise mechanism.
In case it helps, this is the handler function:
function pipeHandler(requiredFunctions) {
//Execute first required function
var executeFunctions = requiredFunctions[0]();
//Execute each subsequent required function using pipe()
for ( var index = 1; index < requiredFunctions.length; index++ ) {
executeFunctions = executeFunctions.pipe(requiredFunctions[index]);
}
//Execute allDone() using pipe()
executeFunctions = executeFunctions.pipe(allDone);
}
Hope somebody has an idea!
Why not
pipeHandler([function() { function1('value'); }, function2]);
?
This is where anonymous functions shine. If you spend some time working in Javascript, you'll probably encounter the same problem when using setTimeOut at some point.
This can be done concisely using bind. Syntax:
pipeHandler([function1.bind(scope, 'value')]);
Bind returns a partial function application, which is a new function in scope scope, with the fixed first parameter 'value'. It'll work with any number of arguments.
You can use an anonymous function, which can invoke the function1
pipeHandler([function () {;
function1('value')
}, function2]);
if you wanna pass parameters without invoking function you may do it like so :
function add (a, b) {
return a + b;
}
// Outputs: 3
console.log(add(1, 2));
// Outputs: function
console.log(add.bind(this, 1, 2));
and this will return a function
function () { [native code] }
if you wanna invoke it
// this will return 3
console.log(add.bind(this, 1, 2)());
What you're probably looking for is called 'Partial application.'
Depending on which browsers you need to support you may be able to simply use bind.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Partial_Functions
As far as I can tell from reading the question, there is no asynchronicity, just a regular single-threaded sequence of function calls, with the possibility of passing parameters at each call.
If so then you want to use jQuery.Callbacks. Your scenario is precisely what jQuery.Callbacks are for. The documentation says :
The jQuery.Callbacks() function, introduced in version 1.7, returns a
multi-purpose object that provides a powerful way to manage callback
lists. It supports adding, removing, firing, and disabling callbacks.
Having read the documentation for jQuery.Callbacks, it's probably still not obvious how to pass parameters to functions in the list.
The simplest option is to fire the list with an object that can be used by the functions in the list :
function myFunction1(obj) {
console.log(obj.myProperty1);
}
function myFunction2(obj) {
console.log([obj.myProperty1, obj.myProperty2].join());
}
var callbacks = $.Callbacks();
callbacks.add(myFunction1);
callbacks.add(myFunction2);
callbacks.fire({
myProperty1: 'X',
myProperty2: 'Y'
});
A more sophiisicated approach allows you :
to specify parameter(s) for each function as it is added to the list, and
to specify a context for all functions in the list
thus giving you two mechanisms for passing data to the functions and the freedom to specify that data in either a .add() statement or a .fire() statement, or both.
For this, you need the following utility function :
function makeClosure(fn) {
var args = Array.prototype.slice.call(arguments, 1);//seriously clever line - thank you John Resig
return function (context) {
fn.apply(context, args);
}
}
which can be used as follows :
function f1() {
console.log(this.myProperty));
}
function f2(value1, value2) {
console.log(value1 + ', ' + value2);
}
function f3(value1, value2) {
//note the use of `this` as a reference to the context.
console.log(value1 + ', ' + value2 + ', ' + this.myProperty);
}
var callbacks = $.Callbacks();
callbacks.add(makeClosure(f1, 'A1'));
callbacks.add(makeClosure(f2, 'B1', 'B2'));
callbacks.add(makeClosure(f3, 'C1', 'C2'));
callbacks.fire({
myProperty: 'Z'
});
DEMO
jQuery's $.proxy(function, context, value) is particularly helpful in this case since it:
Takes a function and returns a new one that will always have a particular context.
Therefore, not only you can change the context of the function being invoked (you can provide an object instead of this), but you can also pass as many arguments/parameters values as the function receives without invoking it directly:
function fun_w_param(v) {console.info("I'm #1, here's my value: " + v)}
function fun_no_param() {console.info("I'm #2")}
function pipeHandler(f1, f2) {
f2();
console.warn("Handling function1 with a second delay");
setTimeout(function(){f1()}, 1000);
}
// add your value below as a proxy's argument
pipeHandler(
$.proxy(fun_w_param, this, '!!!PROXY!!!'),
fun_no_param
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Running the above will delay "function1" execution and it will display the value that you provide into the proxy's parameter.
Using arrow methods you can simply do this
pipeHandler([() => function1('value'), function2]
Related
Is it possible to pass a javascript function with parameters as a parameter?
Example:
$(edit_link).click( changeViewMode( myvar ) );
Use a "closure":
$(edit_link).click(function(){ return changeViewMode(myvar); });
This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.
Use Function.prototype.bind(). Quoting MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
It is supported by all major browsers, including IE9+.
Your code should look like this:
$(edit_link).click(changeViewMode.bind(null, myvar));
Side note: I assume you are in global context, i.e. this variable is window; otherwise use this instead of null.
No, but you can pass one without parameters, and do this:
$(edit_link).click(
function() { changeViewMode(myvar); }
);
So you're passing an anonymous function with no parameters, that function then calls your parameterized function with the variable in the closure
Or if you are using es6 you should be able to use an arrow function
$(edit_link).click(() => changeViewMode(myvar));
Yes, like this:
$(edit_link).click(function() { changeViewMode(myvar) });
You can do this
var message = 'Hello World';
var callback = function(){
alert(this)
}.bind(message);
and then
function activate(callback){
callback && callback();
}
activate(callback);
Or if your callback contains more flexible logic you can pass object.
Demo
This is an example following Ferdinand Beyer's approach:
function function1()
{
function2(function () { function3("parameter value"); });
}
function function2(functionToBindOnClick)
{
$(".myButton").click(functionToBindOnClick);
}
function function3(message) { alert(message); }
In this example the "parameter value" is passed from function1 to function3 through function2 using a function wrap.
I need to write a function:
function doTestConnCall(param1, param2, callbackfun)
param1 & param2 are parameters which I have used inside the function.
The 3rd parameter - callbackfun is a function which to be called after finishing doTestConnCall
How to achieve this?
Is it possible to pass 2 callbacks inside a single method. Say doTestConnCall(param1,callback1,callback2)
Think I am missing some basics. Could any one lead me
You can do something like this:
callbackfun(argument1, argument2);
or:
callbackfun.apply(this, [ argument1, argument2 ]);
or:
callbackfun.call(this, argument1, argument2);
The same can be done with multiple callbacks. For example:
callback1.call(this);
callback2.call(this);
See: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply
And: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call
Functions in JS are top level constructs. That means function hello() {} is the same as var hello = function() {};. So if you want to pass hello to the function above, you can just call doTestConnCall(param1, param2, hello) after you have defined hello() using either method above.
This is how you achieve it.
It is possible to pass what ever you want to as a method parameter.
function doTestConnCall(param1, param2, callbackfun){
DO YOUR LOGIC
callbackfun() // CALL YOUR CALLBACK
}
Call any callback whenever appropriate in the function you are writing--in the case you described, after it completes its core work.
Yes, of course. Call them one after another.
function multipleCallbacks(arg, arg, callback1, callback2) {
// Do some stuff
// Do error checking in the real world if you need to be tolerant
callback1();
callback2();
}
In my code I need to call an object method, retrieve the data from its callback, and pass it to another method or function.
someObject.getSomeData({option1:'value1', option2:'value2'},
function(data) {
doAwesomeStuff(data);
}
);
However, the callback does not recognize any functions/objects/variables outside its scope.
What I've tried to do right now is wrap everything around a function.
var myData = '';
(function(myData) {
someObject.getSomeData({option1:'value1', option2:'value2'},
function(data) {
myData = data;
}
);
});
doAwesomeStuff(myData);
However that doesn't work either.
Anybody know how to properly accomplish this?
You haven't really given us enough to go on there, but this statement:
However, the callback does not recognize any functions/objects/variables outside its scope.
...is incorrect. A function has access to everything in scope where it's defined, so for instance:
var a = 10;
function foo(b) {
bar(5);
function bar(c) {
alert(a + b + c);
}
}
foo(12); // alerts "27"
Note how bar had access not only to c, but also to b (from the call to foo) and a (from the outermost scope shown).
So in your example, the anonymous function you're passing in as the callback has access to everything that's in scope where it's defined; doAwesomeStuff having been defined elsewhere presumably has access to different information, so you'll have to have the callback pass it any data it needs.
So I'm guessing your code looks something like this:
function doAwesomeStuff(data) {
// ...
}
function doSomethingNifty() {
var a = 10,
b = 20;
someObject.getSomeData({option1:'value1', option2:'value2'},
function(data) {
doAwesomeStuff(data);
}
);
}
...and you want doAwesomeStuff to have access to a and b from the call to doSomethingNifty. If so, your only options are to pass them into it as arguments (probably best) or export them to variables some scope that doSomethingNifty and doAwesomeStuff share (probably not ideal, too much like globals).
You can bind required variables to the function passed into the async method.
Also, this SO question has a good treatment of the topic.
Your second version is not going to work at all, since you are trying to immediately access the data that are not yet available (not until the callback has been invoked.)
Your first method:
someObject.getSomeData({option1:'value1', option2:'value2'},
function(data) {
doAwesomeStuff(data);
}
);
looks fine. Please provide more details on what is not working.
One problem could be that getSomeData() does not actually call the callback function.
doAwesomeStuff() can modify many different variables from the received data. The variables which can be accessed by doAwesomeStuff() are those that were available to it (in its scope) where it was created..
Ok hopefully this come across correctly. I am building a universal javascript function that will build a menu and then also build the functions that each menu item would call. To do this, I need to pass a list of the commands to be called for each option.
So for example:
var thecall = 'alert("hi, this works");';
function myfunction(thecall)
{
//In here I want to excute whatever commands is listed in variable thecall
.....
}
I'm sure doing it this way is completely stupid, but I don't know how else to do this.
Basically, I need my function to perform other functions on a variable basis.
Thanks!!
I made it a bit fancier to show you how you can use it.
var thecall = function(name){alert("hi " + name + ", this works");};
function myFunction(function_ref)
{
function_ref('Mark');
}
myFunction(thecall);
You can execute arbitrary strings of JavaScript using eval(), but that is not the best solution for you here (it's almost never the best solution).
Functions in JavaScript are themselves objects which means you can store multiple references to the same function in multiple variables, or pass function references as parameters, etc. So:
var thecall = function() {
alert("hi, this works");
};
function myfunction(someFunc) {
someFunc(); // call the function that was passed
}
myfunction(thecall); // pass reference to thecall
Note that when passing the reference to the thecall function there are no parentheses, i.e., you say thecall not thecall(): if you said myfunction(thecall()) that would immediately call thecall and pass whatever it returned to myfunction. Without the parentheses it passes a reference to thecall that can then be executed from within myfunction.
In your case where you are talking about a list of menu items where each item should call a particular function you can do something like this:
var menuItems = [];
function addMenuItem(menuText, menuFunction) {
menuItems.push({ "menuText" : menuText, "menuFunction" : menuFunction });
}
function test1() {
// do something
}
addMenuItem("Test 1", test1);
addMenuItem("Test 2", function() { alert("Menu 2"); });
// and to actually call the function associated with a menu item:
menuItems[1].menuFunction();
Notice the second menu item I'm adding has an anonymous function defined right at the point where it is passed as a parameter to addMenuItem().
(Obviously this is an oversimplified example, but I hope you can see how it would work for your real requirement.)
I think your looking for the eval function.
var code= 'alert("hi, this works");';
eval(code);
I want to write my own function in JavaScript which takes a callback method as a parameter and executes it after the completion, I don't know how to invoke a method in my method which is passed as an argument. Like Reflection.
example code
function myfunction(param1, callbackfunction)
{
//do processing here
//how to invoke callbackfunction at this point?
}
//this is the function call to myfunction
myfunction("hello", function(){
//call back method implementation here
});
You can just call it as a normal function:
function myfunction(param1, callbackfunction)
{
//do processing here
callbackfunction();
}
The only extra thing is to mention context. If you want to be able to use the this keyword within your callback, you'll have to assign it. This is frequently desirable behaviour. For instance:
function myfunction(param1, callbackfunction)
{
//do processing here
callbackfunction.call(param1);
}
In the callback, you can now access param1 as this. See Function.call.
I too came into same scenario where I have to call the function sent as parameter to another function.
I Tried
mainfunction('callThisFunction');
First Approach
function mainFuntion(functionName)
{
functionName();
}
But ends up in errors. So I tried
Second Approach
functionName.call().
Still no use. So I tried
Third Approach
this[functionName]();
which worked like a champ. So This is to just add one more way of calling. May be there may be problem with my First and Second approaches, but instead googling more and spending time I went for Third Approach.
function myfunction(param1, callbackfunction)
{
//do processing here
callbackfunction(); // or if you want scoped call, callbackfunction.call(scope)
}
object[functionName]();
object: refers to the name of the object.
functionName: is a variable whose value we will use to call a function.
by putting the variable used to refer to the function name inside the [] and the () outside the bracket we can dynamically call the object's function using the variable. Dot notation does not work because it thinks that 'functionName' is the actual name of the function and not the value that 'functionName' holds. This drove me crazy for a little bit, until I came across this site. I am glad stackoverflow.com exists <3
All the examples here seem to show how to declare it, but not how to use it. I think that's also why #Kiran had so many issues.
The trick is to declare the function which uses a callback:
function doThisFirst(someParameter, myCallbackFunction) {
// Do stuff first
alert('Doing stuff...');
// Now call the function passed in
myCallbackFunction(someParameter);
}
The someParameter bit can be omitted if not required.
You can then use the callback as follows:
doThisFirst(1, myOtherFunction1);
doThisFirst(2, myOtherFunction2);
function myOtherFunction1(inputParam) {
alert('myOtherFunction1: ' + inputParam);
}
function myOtherFunction2(inputParam) {
alert('myOtherFunction2: ' + inputParam);
}
Note how the callback function is passed in and declared without quotes or brackets.
If you use doThisFirst(1, 'myOtherFunction1'); it will fail.
If you use doThisFirst(1, myOtherFunction3()); (I know there's no parameter input in this case) then it will call myOtherFunction3 first so you get unintended side effects.
Another way is to declare your function as anonymous function and save it in a variable:
var aFunction = function () {
};
After that you can pass aFunction as argument myfunction and call it normally.
function myfunction(callbackfunction) {
callbackfunction();
}
myfunction(aFunction);
However, as other answers have pointed out, is not necessary, since you can directly use the function name. I will keep the answer as is, because of the discussion that follows in the comments.
I will do something like this
var callbackfunction = function(param1, param2){
console.log(param1 + ' ' + param2)
}
myfunction = function(_function, _params){
_function(_params['firstParam'], _params['secondParam']);
}
Into the main code block, It is possible pass parameters
myfunction(callbackfunction, {firstParam: 'hello', secondParam: 'good bye'});
callbackfunction = () => {}
callbackfunction2(){
}
function myfunction1(callbackfunction) {
callbackfunction();
}
//Exe
myfunction1(callbackfunction);
myfunction1(callbackfunction2.bind(this));
Super basic implementation for my use case based on some excellent answers and resources above:
/** Returns the name of type member in a type-safe manner. **(UNTESTED)** e.g.:
*
* ```typescript
* nameof<Apple>(apple => apple.colour); // Returns 'colour'
* nameof<Apple>(x => x.colour); // Returns 'colour'
* ```
*/
export function nameof<T>(func?: (obj: T) => any): string {
const lambda = ' => ';
const funcStr = func.toString();
const indexOfLambda = funcStr.indexOf(lambda);
const member = funcStr.replace(funcStr.substring(0, indexOfLambda) + '.', '').replace(funcStr.substring(0, indexOfLambda) + lambda, '');
return member;
}