I am trying to reacquaint myself with jQuery and am having difficulty getting started.
In the code below I am trying to say “When the DOM is ready, bind an alert to the change event of the ‘choice’ div, which is actually a select element on a form. When I reload the form though the alert is showing immediately, and does not show when I make a new selection.
Here’s the code:
$(document).ready(doBind());
function doBind() {
$('#choice').change(myAlert('Choice has been changed!'));
}
function myAlert($msg) {
alert($msg);
}
You need to differentiate between function references and invocations (calls). When you associate an event handler or callback you want a function reference which will then be invoked at the proper time. Once you pass arguments and add
(..)(or a nullary()) to a function reference it is invoked. If you do that during binding, then the function will be invoked at binding time and the output of the function will be bound rather than binding the reference (which would allow for the normally expected, later invocation).You should change both of your bindings as follows:
A couple simple examples to highlight the differences in syntax and the use of
().The function below would take a function reference. as an argument and then execute it internally (basically how handlers and callbacks work).
The now popular anonymous function declaration followed by immediate invocation: functions will often be written
function() {...}()which causes the reference to the newly created function to be immediately invoked with any arguments provided (useful in JavaScript to enforce scoping). Arguments in either case are then available as parameters in the function, so whatever is in the invocation(..)maps to what would be declared in thefunction(..)but focusing on reference vs. call is the main issue for your question.