DatsunBing
DatsunBing

Reputation: 9076

Simple binding with jQuery

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);
}

Upvotes: 1

Views: 95

Answers (4)

Matt Whipple
Matt Whipple

Reputation: 7134

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:

   $(document).ready(doBind); //Now a reference to that function

    function doBind() {
        $('#choice').change(function() { myAlert('Choice has been changed!');});    
       //New anonymous function reference which allows for arguments and is conventionally used
    }

    function myAlert($msg) {
        alert($msg);
    }

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).

functionWrapper = function(funk) {
  //Do something else
  funk()
}

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 the function(..) but focusing on reference vs. call is the main issue for your question.

Upvotes: 4

Barmar
Barmar

Reputation: 780974

All the answers given so far are very good. However, what they haven't mentioned is that this is not how one generally writes jQuery code. Usually there are many things you want to initialize when the document is loaded. So the way things are practically always written is with an anonymous function whose body is all your local variables, functions, and initializations. So rather than have a separate doBind() function, you would write:

$(document).ready(function () {
    $('#choice').change(myAlert);
    function myAlert($msg) {
        alert($msg);
    }
});

Since this is so common, jQuery provides a short-hand notation for it:

$(function () {
    $('#choice').change(myAlert);
    function myAlert($msg) {
        alert($msg);
    }
});

If you want to stick with your separate, named function, you can write:

$(doBind);

Upvotes: 1

MushinNoShin
MushinNoShin

Reputation: 4886

$(document).ready(doBind);

function doBind() {
    $('#choice').on('change', function(){alert('Choice has been changed!')});
}
  1. Pass functions as objects. () executes the function, leaving that off treats it as an object. When indicating a callback, you're passing the function as an object (unless the function you're executing returns a function object, this is referred to as currying).

  2. $.on is the preferred way to bind events in the latest jquery. You can find it's documentation here.

  3. Generally create your functions like this: var doBind = function() { //doBind stuff } This helps to recognize that you're passing functions around as objects and it also prevents them from cluttering up the global namespace.

Hope this helps :)

Upvotes: 2

Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

Function my alert must be like this:

function myAlert($msg) {
    return function() {
        alert($msg);
    }
} 

This is because you need to pass a function to change. When you do myAlert('Choice has been changed!'), what you are passing is not the function myAlert but its result after execution.

Upvotes: 2

Related Questions