Why is this javascript function running without being called? - javascript

$(document).ready(SetupButtonClicks());
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff());
}
function DoPHPStuff() {
//stuff
}
I have this code in my javascript file, when I debug it I see it call SetupButtonClicks() like it should but after that is done it calls DoPHPStuff(). DoPHPStuff() should only be called when btnJavaPHP is clicked. What am I doing wrong?

Change your SetupButtonClicks function:
$('#btnJavaPHP').click(DoHPStuff);
The way you've got it coded, you're telling Javascript to call the function, not to use it as the "click" handler. The parentheses are an operator that causes a function to be called.

Remove the ().
By writing $(document).ready(SetupButtonClicks()), you are calling SetupButtonClicks and passing its return value to ready.
Similarly, by writing $('#btnJavaPHP').click(DoPHPStuff()), you are calling DoPHPStuff (immediately) and passing whatever it returns to click().
You need to pass the functions themselves by writing $(document).ready(SetupButtonClicks) and $('#btnJavaPHP').click(DoPHPStuff).

function DoPHPStuff() {
//stuff
}
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff);
}
$(document).ready(SetupButtonClicks);

With the exception of a function declaration, a pair of parentheses following a function's identifier causes the function to execute. Examples:
// function declaration; function not executed
function SetupButtonClicks() {
}
// function executed
SetupButtonClicks();
// function not executed
SetupButtonClicks;

Related

How to use JS callbacks?

I have some really hard times understanding JS callbacks. From what I understand is that JS callback is a function that takes the argument of another function. So let's say I have a function called myFunction and passes mySecond to it, will it exicute myFunction before mySecond?
function myFunction(){
alert("hello");
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
if you want myFunction before mySecond. The code is below.
function myFunction(func){
alert("hello");
func();
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
Hello, if you want myFunction after mySecond. The code is below.
function myFunction(func){
func();
alert("hello");
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
a JS callback is a function that takes the argument of another function
This "understanding" is confused and has it backwards:
a JS callback is a function provided as an argument to another function, to be called back after the called function has done something.
A classic example or callback function is provided by the syntax of setTimeout:
setTimeout( callback, 1000);
Here callback (a function) is called back (by setTimeout) after a second has elapsed.

how to call function-1 inside function-2

I have function-1
$('.make_favorite').live('click', function() {
//some code here
});
I have another function-2
function selectContactTab() {
//some code here
//call function-1 here
}
for some reason I do not have control over function-1,
My Question is how to call function-1 inside function-2?
You can manually fire the click event, which will result in the anonymous function, what you state as Function-1, being run...
function selectContactTab() {
//some code here
//call function-1 here
$('.make_favorite').click();
}
Your Function-1 is actually function call, with a callback passed in. You need to wrap it inside it's own function, something like this:
function functionOne() {
//some code here
}
function selectContactTab() {
//some code here
functionOne();
}
$('.make_favorite').live('click', functionOne);
In this example, functionOne is a function on the scope, and is also being passed in as the callback for your .live call. The reason it didn't work before was because the callback in your function-1 was outside of the scope your function-2 was in - put simply, it didn't exist. Initialising it in a function like in my example will make it available to call.

Why is it not required to have '()' at the end of the success function?

I got the following code:
navigator.geolocation.getCurrentPosition(
successFunction
);
I was wondering why it is not required to use the '()' at the end of the succesFunction? Isn't it required to call a function with the '()' --> somefunction()
What's the logic behind it?
Because you're passing in the function reference, not the returned value of the function.
A function is a thing that can be invoked—where it runs code and returns a result. You invoke a function by using the parentheses. But, if you want to talk about the thing, if you want to pass the function around so that someone else can invoke it, you leave off the parentheses.
In this case, the getCurrentPosition() function is asking you to give it a function so that it can call it later on. So instead of invoking successFunction, you pass along a reference to it.
If you instead wrote:
navigator.geolocation.getCurrentPosition(
successFunction()
);
…then what would happen is successFunction() would be invoked—the code of the function would be run, and possibly return a value—and THEN you would invoke getCurrentPosition(), passing along as an argument whatever value successFunction returned.
In JavaScript you can pass functions as objects:
Try executing this example:
function myFunction() {
console.log('hello');
}
function anotherFunction(functionParameter) {
console.log('executing function passed as argument:');
functionParameter();
}
anotherFunction(myFunction);
This code will print:
"executing function passed as argument:"
"hello"

Calling javascript functions without parenthesis

When i was reading some code of jquery then i found this in one of their widgets
option: {
_page: this._getPage,
_panelInner: this._getPanelInner()
},
_getPage : function(){ //code goes here that returns something..},
_getPanelInner : function(){ //code goes here that returns something..}
I wanna know how's the first this._getPage function is being called without parenthesis. And if functions can be called like this then why the next function _getPanelInner is being called with parenthesis..?
_panelInner will hold the value returned by the _getPanelInner function while _page will hold a reference to the _getPage function. This means that the function would be able to be called in one of the following ways:
option._page()
this._getPage()
Both of these function calls would execute the same function but that function is not called automatically (according to the code that is displayed).
It's not getting called, it's only having a reference to the function so later you can do:
option._page();

Why is function() needed sometimes in JavaScript?

HTML
<button id='hello'>Click Me!</button>
JavaScript (wrong)
$('#hello').click(alert('Hello, World!'));
JavaScript (correct)
$('#hello').click(function() {
alert('Hello, World!');
}
I'm wondering why the first JS code triggers on the event load instead of click. Can anyone tell me why function() { [code] } is needed for the script to work properly?
In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout, too.
The click function expects another function as a parameter.
In the first case you would be passing the result of calling alert('hello world');, which is null.
The second is just a shorthand for:
$('#hello').click(callback);
function callback(){
alert('hello world');
}
Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert) and then pass it's return value.
Writing $('#hello).click( function() { } )` is basically a short hand for writing:
var myfunction = function() {
// code
};
$('#hello').click( myfunction );
As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.
Your first example says "evaluate
alert('Hello, World!')
right now, and pass the result as an argument to click. "
The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.
The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.
You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:
function returnCallback(linkId, data) {
return function(e) {
alert('Clicked on ' + linkId + '. Here is some data: ' + data);
// Maybe do some stuff with e, the event parameter
}
}
$('#some-link').click(returnCallback('some-link', 'some-data'));
$('#other-link').click(returnCallback('other-link', 'different-data'));
This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.
In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.
$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.
This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:
<script language="javascript" type="text/javascript">
$("#mybutton").click(clickFired);
function clickFired() {
alert('click fired');
}
</script>
The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().
The click function here assigns a value to the event handler.
With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.
With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.
somefunction(alert('hello! world'));
this would mean you want to pass to somefunction the return value of alert("hello! world").
jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.

Categories