views:

467

answers:

3

Recently making the switch from Prototype to jQuery, I am struggling with some basic issues.

I use several AJAX-requests in my application; for 95% of these requests, I'd like to have some global events executed, such as showing or hiding a loading indicator. Apart from the global functionality, every request should also have some custom code executed after it has completed.

It seems like the local Ajax events override the global ones, once they are set. For example, see the following code:

// global events
$('#loader').bind('ajaxStart', function() { 
    // in this particular example, the ajaxStart() works fine, 
    // as it has not been overridden
    Loader.enable();
}).bind('ajaxComplete', function() { 
    // this section will not execute. when the local complete()
    // is removed, it will execute just fine
    Loader.disable();
} );

// local ajax event
$.ajax({
    type: $(element).attr('method'),
    url: $(element).attr('action'),
    data: $(element).serialize(),
    global: 'true',
    complete: function(data) {
     if (params.target && $('#' + params.target)) {
      $('#' + params.target).html(data.responseText);
     }
     Behaviour.apply();
});

In this particular case, the local complete() event seems to stop the global ajaxComplete() event from executing.

Is there any way to execute both the local as the global ajax events?

+3  A: 

I haven't tried it, but why aren't you creating a global method:

function globalAjaxComplete(data)

and call it from both the global and local event handler?

You could also define a class "ajaxEnabled" and do this:

$(".ajaxEnabled").bind("ajaxStart", 
   Function() { globalAjaxComplete(); });

Then you wouldn't need to call the global method every time.

Still don't know however why the local binding cancels the global one.

kgiannakakis
I haven't tried this yet, but it will undoubtly work. This would require me to use this structure for every AJAX-request, though, which does not really improve my code.
Aron Rotteveel
+4  A: 

Just tried to run your code. Added the missing }); though. Worked like a charm. Calls were made in this order:

  1. ajaxStart
  2. complete
  3. ajaxComplete

Here is what I did:

// local ajax event
$.ajax({
    ...
    global: 'true',
    complete: function(data) {
        ...
    }
}); // <=== This line here
Uzbekjon
Error has been fixed now, but was caused by an wrong paste. This does not solve my problem.
Aron Rotteveel
A: 

First of all, thank you for the replies. Both of them at least helped me to re-evaluate my code time and time again.

The problem and solution turned out to be quite simple:

The Behaviour.apply(); that was called in my local complete event triggered an error elsewhere, preventing the complete() function to finish correctly and effectively disabling the global ajaxComplete() event. Fixing this error also fixed my problem.

This means that jQuery supports combining both local as global ajax events.

Aron Rotteveel