Yet another javascript function scope question - javascript

In this code, the ident and data variables are correct in the callback, but I don't know how to pass in the right i for each loop iteration. I've tried reading up on functions and tried like 10 things, but alas, I must seek the wisdom of the stack.
function callback()
{
$(ident).html( data.fields[i].value );
$(ident).fadeTo('slow',1);
}
for(i=0;i<data.fields.length;i++)
{
ident='#'+data.rID+'_'+data.fields[i].field;
$(ident).fadeTo('slow',0,callback);
}

Change your "callback" function:
function callback(i) {
return function() {
$(ident).html( data.fields[i].value );
$(ident).fadeTo('slow',1);
};
}
Then in your loop:
$(ident).fadeTo('slow',0,callback(i));
This "callback" implementation returns the function that you'll pass to "fadeTo()".

One way would be to declare the callback function within the for loop.

My original answer was incorrect. Thanks to #Pointy for the heads-up.
This is similar to #Pointy's answer, but has different placement for the closure.
function callback(k) {
$( this ).html( data.fields[k].value );
$( this ).fadeTo('slow',1);
}
for(i=0;i<data.fields.length;i++) {
(function(j) {
ident='#'+data.rID+'_'+data.fields[j].field;
$(ident).fadeTo('slow',0, function() { callback.call( this, j) });
})(i);
}

You can use an anonymous function instead of the pointer to callback, so that you can pass in i to callback.
function callback(i, elem)
{
$(elem).html( data.fields[i].value );
$(elem).fadeTo('slow',1);
}
for(i=0;i<data.fields.length;i++)
{
var ident='#'+data.rID+'_'+data.fields[i].field;
$(ident).fadeTo('slow',0,function() { callback(i, this); });
}
Rather than making ident a global variable, it would be best to declare it (making it constrained to the current function's scope), and then use this in the callback to reference that element.
If you're not using callback anywhere else, it may make sense to just put its implementation inside of the anonymous function, rather than defining it separately and calling out to it:
for(i=0;i<data.fields.length;i++)
{
ident='#'+data.rID+'_'+data.fields[i].field;
$(ident).fadeTo('slow',0,function() {
$(ident).html( data.fields[i].value );
$(ident).fadeTo('slow',1);
});
}
The above example with the inline anonymous function doesn't work, because the reference to i is shared between the callbacks.

Related

Javascript invoke function without parentheses [duplicate]

How do I pass a function as a parameter without the function executing in the "parent" function or using eval()? (Since I've read that it's insecure.)
I have this:
addContact(entityId, refreshContactList());
It works, but the problem is that refreshContactList fires when the function is called, rather than when it's used in the function.
I could get around it using eval(), but it's not the best practice, according to what I've read. How can I pass a function as a parameter in JavaScript?
You just need to remove the parenthesis:
addContact(entityId, refreshContactList);
This then passes the function without executing it first.
Here is an example:
function addContact(id, refreshCallback) {
refreshCallback();
// You can also pass arguments if you need to
// refreshCallback(id);
}
function refreshContactList() {
alert('Hello World');
}
addContact(1, refreshContactList);
If you want to pass a function, just reference it by name without the parentheses:
function foo(x) {
alert(x);
}
function bar(func) {
func("Hello World!");
}
//alerts "Hello World!"
bar(foo);
But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:
function foo(x) {
alert(x);
}
function bar(func) {
func();
}
//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });
If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:
function eat(food1, food2) {
alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args) {
//do stuff
//...
//execute callback when finished
callback.apply(this, args);
}
//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]);
Example 1:
funct("z", function (x) { return x; });
function funct(a, foo){
foo(a) // this will return a
}
Example 2:
function foodemo(value){
return 'hello '+value;
}
function funct(a, foo){
alert(foo(a));
}
//call funct
funct('world!',foodemo); //=> 'hello world!'
look at this
To pass the function as parameter, simply remove the brackets!
function ToBeCalled(){
alert("I was called");
}
function iNeedParameter( paramFunc) {
//it is a good idea to check if the parameter is actually not null
//and that it is a function
if (paramFunc && (typeof paramFunc == "function")) {
paramFunc();
}
}
//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled);
The idea behind this is that a function is quite similar to a variable. Instead of writing
function ToBeCalled() { /* something */ }
you might as well write
var ToBeCalledVariable = function () { /* something */ }
There are minor differences between the two, but anyway - both of them are valid ways to define a function.
Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:
anotherFunction(ToBeCalledVariable);
There is a phrase amongst JavaScript programmers: "Eval is Evil" so try to avoid it at all costs!
In addition to Steve Fenton's answer, you can also pass functions directly.
function addContact(entity, refreshFn) {
refreshFn();
}
function callAddContact() {
addContact("entity", function() { DoThis(); });
}
I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :
function foo(blabla){
var func = new Function(blabla);
func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");
And that's working like a charm ... for what I needed at least. Hope it might help some.
I suggest to put the parameters in an array, and then split them up using the .apply() function. So now we can easily pass a function with lots of parameters and execute it in a simple way.
function addContact(parameters, refreshCallback) {
refreshCallback.apply(this, parameters);
}
function refreshContactList(int, int, string) {
alert(int + int);
console.log(string);
}
addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array
You can also use eval() to do the same thing.
//A function to call
function needToBeCalled(p1, p2)
{
alert(p1+"="+p2);
}
//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
eval(aFunction + "("+params+")");
}
//A function Call
callAnotherFunction("needToBeCalled", "10,20");
That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.
Here it's another approach :
function a(first,second)
{
return (second)(first);
}
a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world
In fact, seems like a bit complicated, is not.
get method as a parameter:
function JS_method(_callBack) {
_callBack("called");
}
You can give as a parameter method:
JS_method(function (d) {
//Finally this will work.
alert(d)
});
The other answers do an excellent job describing what's going on, but one important "gotcha" is to make sure that whatever you pass through is indeed a reference to a function.
For instance, if you pass through a string instead of a function you'll get an error:
function function1(my_function_parameter){
my_function_parameter();
}
function function2(){
alert('Hello world');
}
function1(function2); //This will work
function1("function2"); //This breaks!
See JsFiddle
Some time when you need to deal with event handler so need to pass event too as an argument , most of the modern library like react, angular might need this.
I need to override OnSubmit function(function from third party library) with some custom validation on reactjs and I passed the function and event both like below
ORIGINALLY
<button className="img-submit" type="button" onClick=
{onSubmit}>Upload Image</button>
MADE A NEW FUNCTION upload and called passed onSubmit and event as arguments
<button className="img-submit" type="button" onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>
upload(event,fn){
//custom codes are done here
fn(event);
}
By using ES6:
const invoke = (callback) => {
callback()
}
invoke(()=>{
console.log("Hello World");
})
If you can pass your whole function as string, this code may help you.
convertToFunc( "runThis('Micheal')" )
function convertToFunc( str) {
new Function( str )()
}
function runThis( name ){
console.log("Hello", name) // prints Hello Micheal
}
You can use a JSON as well to store and send JS functions.
Check the following:
var myJSON =
{
"myFunc1" : function (){
alert("a");
},
"myFunc2" : function (functionParameter){
functionParameter();
}
}
function main(){
myJSON.myFunc2(myJSON.myFunc1);
}
This will print 'a'.
The following has the same effect with the above:
var myFunc1 = function (){
alert('a');
}
var myFunc2 = function (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
Which is also has the same effect with the following:
function myFunc1(){
alert('a');
}
function myFunc2 (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
And a object paradigm using Class as object prototype:
function Class(){
this.myFunc1 = function(msg){
alert(msg);
}
this.myFunc2 = function(callBackParameter){
callBackParameter('message');
}
}
function main(){
var myClass = new Class();
myClass.myFunc2(myClass.myFunc1);
}

Javascript - How to put a callback in a callback?

I have read this:
Callback in a callback?
And I still do not understand how I am meant to do it. Sorry, I am a Python programmer and only just starting to understand JavaScript.
I have this function:
this.getName(function() {
alert("Done");
});
Which has a callback to here:
this.getName = function(callback){
*doing something*
callback();
}
Which works great. The alert doesn't go off until getName() has finished.
However I have another function, which needs to be run after getName() has been run and completed:
this.getDetails = function(){
*Does something*
}
But I haven't got a clue how it is meant to be implemented. I have tried putting it in the first function, but it doesn't work. Any help would be much appreciated!
I have tried this:
this.getName(function(getDetails) {
alert("Done");
this.getDetails();
});
Instead of alerting "done", just call getDetails (or do both):
this.getName( _ => {
this.getDetails();
} );
I switched to an arrow function to use lexical this, but if you don't want to use an arrow function you can also use bind:
this.getName( function ( ) {
this.getDetails();
}.bind( this ) );
or just:
this.getName( this.getDetails.bind( this ) );

Understanding JavaScript Closures - Freeze variable passed to callback

I do not yet have a basic understanding of JavaScript closures;
I have a question regarding a specific situation that perhaps is also basic and common example:
Count from 1 to 3 in 3 seconds
See JSFiddle here: http://jsfiddle.net/nAh8x/
The code:
var i,
t;
t = 0;
// Case A
for( i=1; i<=3; i++ ) {
setTimeout( function() { log(i); }, t );
t += 1000;
}
// Case B
for( i=1; i<=3; i++ ) {
setTimeout( wrapper(i), t );
t += 1000;
}
function wrapper(i) {
return function() { log(i); };
}
// Log utility function
function log(msg) {
$('#log').append( msg + '<br />' );
}
Case A doesn't work.
It's clear to me why: every time the function inside setTimeout is called and accesses the i variable, its value has already reached 4.
Case B works.
When wrapper(i) is called it returns
function() { log(i); };
and the above return value (a function) is what goes inside setTimeout. What goes inside setTimeout is exactly the same as Case A
But this time, the i variable have been "frozen" with the value at the time of the call.
Why using the wrapper function let the passed value to be frozen?
That's not completely clear to me.
Closure is an environment which is created with variables scope and nested function by calling of outer function,
Every time the wrapper() is called there would created each different environment for below's function
function wrapper(i) {
return function() { log(i); };
}
Here is the i's value would be same as when wrapper() is invoked. Each time the i's value would be private for that particular environment which made by invoking wrapper() outer function.
The wrapper function has it's own i that is locally scoped to it.
This receives the value of the other i at the time wrapper is called.
It might be clearer if you rewrote it as:
function wrapper(notI) {
return function() { log(notI); };
}
The variable i used inside wrapper is the one the has been passed (as a copy) as the formal parameter to wrapper. It's not the same i as the one inside your for loop - you could rename that variable to anything you like and the code would still work.
It's frozen because it has the value it had each time wrapper was originally called.

Any way to avoid using anonymous functions in jQuery?

If I have a chunk of code like this:
.hover(
function () {
hoverState($("#navbar a").index(this),1);
},
function () {
hoverState($("#navbar a").index(this),-1);
});
Is there any way to get rid of the anonymous functions and just say:
.hover(
hoverState($("#navbar a").index(this),1),
hoverState($("#navbar a").index(this),-1);
);
No, because otherwise your call:
hoverState($("#navbar a").index(this),1)
would evaluate at the same time as the call to the hover function itself. Since Javascript supports closures and first-class functions, you could make a wrapper function:
function wrapper(position){
function _f(){
hoverState($("#navbar a").index(this), position);
}
return _f;
}
And then use:
.hover(
wrapper(1),
wrapper(-1),
)
But the gains of such an approach are questionable.
The reason for the anonymous function is to defer the call to hoverState until the hover event happens. Without some function reference there, you end up calling hoverState and the result of the function call becomes the parameter to the hover method, which is certainly not what you want. The alternative would be to have a named function, but that's really no better and, in some ways, actually worse.
There's a way to do something like this, with the jLambda plugin.
// Without plugin:
$('.foo').click(
function() {
$(this).hide();
$('p').show();
$('a').width(20);
});
// With plugin:
$('.foo').click($l.hide().$('p').show().$('a').width(20));
My answer can seem stupid but here goes... you can use simple functions :}
function hoverStateProxy1() {
hoverState($("#navbar a").index(this),1);
}
function hoverStateProxy2() {
hoverState($("#navbar a").index(this),-1);
}
.hover(hoverStateProxy1, hoverStateProxy2);
As long as you passing reference to function you are OK. It can be both anonymous or not.
You could use JavaScript's "Apply" Function. Here is an example taken from the Prototype.js framework (bind implementation, though it should probably be renamed if not being used from within the framework).
EDIT: Corrected, see This Post
if (!Object.bind) {
Function.prototype.bind= function(owner) {
var that= this;
var args= Array.prototype.slice.call(arguments, 1);
return function() {
return that.apply(owner,
args.length===0? arguments : arguments.length===0? args :
args.concat(Array.prototype.slice.call(arguments, 0))
);
};
};
}
Usage:
.hover(
hoverState.bind(this,$("#navbar a").index(this),1),
hoverState.bind(this,$("#navbar a").index(this),-1)
);

JQuery callback question

I'm trying to assign a different number to different callback functions in jquery.
for (i=o;i<types.length;i++) {
$('#ajax'+types[i]+'Div').html('Loading...').load('searchAjax.php','new=u',function () { $(this).find('select').change( function() { AjaxDiv(i); } ) } );
}
Everytime I run this section of code, i is 5 for each call to ajaxDiv because it is calling a global variable. I'm not sure if I can either change the scope of i or if there's a way to print the value in the change function. Any ideas?
Thank you in advance! Happy Thanksgiving!
Andrew
The callback functions all refer to the same i variable, and they are executed when the loop is finished.
You have to capture the i variable on the loop:
for (i=o;i<types.length;i++) {
(function (i) {
$('#ajax'+types[i]+'Div').html('Loading...').load('searchAjax.php','new=u',
function () {
$(this).find('select').change( function() { AjaxDiv(i); } )
} );
})(i);
}

Categories

Resources