views:

34

answers:

2

I've dug the manual and tried extensivelly to drop the extra function(){...} call after the error and success to do it like mootools but to no good luck.

Is there any way i can avoid the extra function in jQuery?

function doFileDelete(ui) {
    $.ajax({
        error: function() { doFileDeleteAnimation(ui, false) },
        success: function() { doFileDeleteAnimation(ui, true) },
        url: '/url-to-delete-file'
    });
}

Thank you!

+1  A: 

If you have no arguments in the function you would like to call, yes, you can just pass the name of the function as your parameter for your callback. However, if you have at least one argument, you must declare the function and pass the necessary data.

Read more in the jQuery documentation regarding callbacks.

Jason
Thanks Jason! I've dug into the API and missed all the how-to's. I find jQuery's manual, so far, a bit sparser than the moo one. Nevertheless thank you for the great advice.
Frankie
it's actually pretty good. check this out: http://www.futurecolors.ru/jquery/
Jason
Very useful! Already printed and sitting above my screen! Thank you very much!
Frankie
it's actually my comp's wallpaper :) glad i could help
Jason
+1  A: 

You could also eliminate that outer function by using Function.prototype.bind (either the Prototype library version or the ECMAScript 5 native version if your browser supports it). For example:

function handler(myBoolean) {
  console.log(myBoolean); // will output true
}

$(function() {
  $('#test').click(handler.bind(this, true));
});

The first argument to bind is the context you want to execute the function within. Subsequent parameters are passed to the handler function. When jQuery executes handler as a callback, the function calls are curried and the parameters it passes will be tacked onto the ones you specified in your bind call. So, in my example handler would receive three parameters when you click on #test: the boolean you passed in, the event object, and the DOM element that was clicked.

jQuery has a rough equivalent of bind with its function $.proxy. By default, it doesn't allow you to curry functions like bind does, but someone wrote an extension to it that will give it that functionality.

In my opinion, bind is a better choice than $.proxy since it has cleaner syntax, doesn't require you to monkey patch jQuery, and will be supported natively by browsers once ECMAScript 5 is fully implemented.

Jimmy Cuadra
Thank you! This will sure be a nice workaround to some of the more complex part of the program I'll have to dwell into latter!
Frankie