Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to assign functions to variable, using jquery

so I've been messing around with some Jquery Ajax promises/deffers etc... and i've come across something I don't completely understand, not strictly related to the Jquery Ajax.

I have always declared and called functions like so:

function foo1() { //sets function
    alert('foo1');
}

foo1(); //calls function

But it seems the more I see different code a lot of people are declaring functions like the following, I just copied and pasted an example I saw so I would't miss anything:

var promise = $.ajax({
    url: "/myServerScript"
});

promise.done(myStopAnimationFunction);

I understand what the above does, just an example.

The question is, is it better to assign functions to variables? What are the pros/cons, and in what situations is this way used? At what point in this code is the actual function called. Does

    promise.done(myStopAnimationFunction);

call both the ajax function, and then the callback, or just the callback?

Thanks

like image 960
JamesGP Avatar asked Jun 21 '26 11:06

JamesGP


1 Answers

In your example, you're assigning your promise variable to what $.ajax returns (which is a jqXHR object)

var promise = $.ajax({
    url: "/myServerScript"
});

Your then saying that once it's done, you want to call myStopAnimationFunction. Because $.ajax is async by default, the browser will skip right over this and only call your myStopAnimationFunction when the request is complete.

promise.done(myStopAnimationFunction);

Now, with your myStopAnimationFunction; you could always just do the following:

promise.done(function(){
    $('.loader').hide();
});

but if you have code which you'll be using a lot, put it in a function so you don't need to repeat yourself (see DRY) - this has nothing to do with jQuery, however.

Your example is exactly the same as doing:

$.ajax({
    url: "/myServerScript"
}).done(function(){
    $('.loader').hide();
});
like image 147
Prisoner Avatar answered Jun 23 '26 01:06

Prisoner