jQuery function vs handlers [duplicate] - javascript

This question already has answers here:
what is the difference between calling function in JavaScript with or without parentheses ()
(4 answers)
Closed 9 years ago.
A simple question from someone trying to learn:
I have this:
$(function(){$("#topFlag").hover(changeFlag, setFlag ); });
function changeFlag(){
//some code
};
function setFlag(){
//somecode
};
And it's all working (now). But what I expected to use was:
$(function(){$("#topFlag").hover(changeFlag(), setFlag() ); });
What's the difference? Why doesn't changeFlag() (with the parens) work? Isn't this a function call? What if I wanted to pass a parameter to the function?
Thanks for any insights (or pointers to documentation I can read). I've already checked out:
http://api.jquery.com/hover/
http://www.w3schools.com/js/js_functions.asp

changeFlag is a function.
changeFlag() calls that function.
You need to pass the function. You don't need to call the function and pass its return value.

When you add braces after a function name , it executes the function
setFlag() ; // calls the function
But you want the function to fire , when you hover over the element
And not at the time of attaching the event

In javascript the functions are also variables, when you pass it as a parameter you want to send the function to execute, if you write this yourFunc() you would be sending the result of that function instead.
To send parameter I use this:
$(function(){$("#topFlag").hover(function(){changeFlag(param1, param2,...)}, function(){setFlag(param1, param2,...)}); });
this creates an anonym function that call your functions.

Related

Unexpected behaviour calling function from function [duplicate]

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 2 years ago.
Recently I started learning about JS, and I got stuck in the following issue:
I am trying to call a function "draw_point" when a "mousemove" event happens.
When trying the following, the code works as expected (the function gets called):
svg.on('mousemove', draw_point(true));
But when replacing the caller function like this, it stops working and I don't get any error messages to troubelshoot.
svg.on('mousemove', function () {
draw_point;
});
Any explanation of what is going on?
Both examples are wrong, but for different reasons. In the first, you're calling the functiondraw_point immediately and passing its return value to the .on call. In the second, you're creating an anonymous function that wraps draw_point, but you're not calling draw_point. This is legal because javascript allows empty statements like myVar; or 3;.
What you want to do is pass the function draw_point, but not call it. It will be called when the handler runs:
svg.on('mousemove', draw_point);

Using the function inside a function in Javascript [duplicate]

This question already has answers here:
Javascript call nested function
(11 answers)
Closed 6 years ago.
Can anyone please help me in this? I have declared a function inside a function and now want to call only that function.
For example:
function hello(){
alert("Hello");
function insideHello(){
alert("insideHello");
}
}
I just want to call the insideHello function.
I know one way is to call (new hello()).insideHello(); by declaring this.insideHello = function. I don't want to use new every time because I am using this in canvas scenario.
You could make hello a "module" that exposes insideHello as part of its API:
function hello() {
alert("Hello");
function insideHello() {
alert("insideHello");
}
return {
insideHello // or insideHello: insideHello
}
}
hello().insideHello()
I would have two functions and you call the second one from inside the first - but you can call the second one separately as well (of course the names wont mean much in this example).
function hello(){
alert("Hello");
insideHello();
}
function insideHello(){
alert("insideHello");
}
That way you can get both the outer and inner function by calling hello(); and just the inner function by calling insideHello(); ... again noting that the names are not very descriptive since i removed the inner function to the outside. But it seems that if you want to only call the inner one then you shouldn't need to call the outer one. and if you want to call both then the outer one should be able to handle that.

Cannot assign value to variable by reference in Javascript [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I would like to assign value to the variable IMLoginReq inside a ProtoBuf load function, but its not working, can anyone help?
var IMLoginReq;
protobuf.load("./pb/IM.Login.proto", (err, root) => {
// Obtain a message type
IMLoginReq = root.lookup("IM.Login.IMLoginReq");
console.log(IMLoginReq);//<== is not undefined
});
console.log(IMLoginReq);//<== is undefined
The load() method is asynchronous. As such the console.log at the end will happen before the load finishes. Instead of trying to treat this as procedural logic, which it is not, you should instead use the IMLoginReq inside the success method that you have.
Thats because you are trying to call it before its loaded. You should have a callback function like success so it will be there.
You can also use promises by omitting the callback:
protobuf.load("awesome.proto")
.then(function(root) {
...
});

$.when().done() is firing the done function before when completes [duplicate]

This question already has answers here:
How do you work with an array of jQuery Deferreds? [duplicate]
(4 answers)
Closed 6 years ago.
I have a page like this:
$(document).ready(function() {
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall());
});
For some reason the finalCall() is firing simultaneous to the three calls surrounded by $.when().
I tried calling a reference to the finalCall() function as in:
$(document).ready(function() {
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall);
});
But even then, it still fires the function before the prior 3 complete.
NOTE: I am not including the functions here as they are not relevant. I just need to know why the finalCall() function would fire simultaneous to then $.when() functions.
Thank you.
$.when does not call your callback at all. You are doing it yourself:
// vv
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall());
// ^^
Change that to
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).then(finalCall);
where the function is actually passed into the promise method, and it'll work (assuming your ajax functions return promises).

Use a variable as function in jquery [duplicate]

This question already has answers here:
Javascript dynamically invoke object method from string
(5 answers)
Closed 8 years ago.
I want to use a method in which i will pass a function_name as parameter to another function.
On the other function, the parameter will be treated as a function
here's my code example
<div class="btn_crt_acct" onclick="toggle_object('register_div','slideDown');">
CREATE AN ACCOUNT
</div>
whch will call a function like this
function toggle_object(obj,fun)
{
$('#'+obj).fun('slow');
// fun => slideDown
// so $('#'+obj).fun('slow'); => $('#'+obj).slideDown('slow');
}
but i am doing something wrong as it states an error in console, $fun(..) is not a function.
How can i make it work perfectly??
Thanks
You'd do that with bracket notation
$('#'+obj)[fun]('slow');
FIDDLE
But why not use a proper event handler, and slideToggle if you intend to toggle it
$('.btn_crt_acct').on('click', function() {
$('#register_div').slideToggle();
});

Categories