Why a Cordova function executes at page load

I have recently been experimenting with the Cordova libraries to create cross-platform mobile applications using Visual Studio 2015. If you are interested in learning about Cordova, I found this tutorial to be very helpful.

Being new, I just wanted to go off-script and create a button to say “Hi”. So I had a basic HTML page with a reference to my JavaScript file (I have ripped out all the other code to make the example more readable):

<!DOCTYPE html>
<html>
<head>
    http://scripts/find.js
</head>
<body>
    <button id="find" data-role="button">Find</button>
</body>
</html>

In my JavaScript file, find.js, I had a simple method to display the results of a JS alert:

$(document).ready(function () {
    $('#find').bind("click", alert('Hi'));
});

My expectation was that this would only execute when I click the button, which my years of development experience led me to believe. But things were different here, and I was getting the “Hi” message when my application loads.

Luckily, I found a nice Stack Overflow post explaining the problem, and the solution. To fix this behavior, I had to stick the alert call into a method and modify the bind statement:

$(document).ready(function () {
    $('#find').bind("click", alerty);
});
function alerty() {
    alert('Hi');
}

Notice that when I reference “alerty” in the bind statement, I don’t include any parentheses.

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: