views:

38

answers:

2

I've been playing around with subscribing elements to AJAX events in jQuery.

I have an element that I am using to load AJAX response's. This element is only displayed IF there is data pertinent to the current context of the program.

So, I thought it would be nice and easy to .show() whenever an AJAX request has completed on it and hide it when I need to. I would like to remove the need to implicitly .show() the element every time I make an AJAX request.

In jQuery there is .ajaxSuccess() and .ajaxComplete(). These however, will fire when any AJAX request completes/succeeds, so when loading data in other parts of the page, my hidden element will .show().

The solution seems to be (per. the jQuery API reference) to use the ajaxOptions parameter in your event handler function:

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxComplete handler.');
  }
});

What I don't understand is the reason for registering an event handler for all AJAX requests to a specific element, besides being able to use $(this). Am I missing something, can I register an event handler for an AJAX request specific to an element?

If not, is there any event driven alternative to using the .url? The reason I ask is that I use the page fragment extensively for tracking page state and it would be easier to have an event handler .show() my element whenever an AJAX request loads data into it.

EDIT: Post title grammar.

A: 

My thinking, is that you want something like this:

$(document).ajaxComplete(function(e, xhr, settings) {
    if(settings.url == 'ajax/test.html') {
      $('#foo').text('Triggered ajaxComplete handler.');
    } else if(settings.url == 'ajax/another.html') {
      $('#bar').text('Triggered ajaxComplete handler.');
    }
});

Does that make sense, or am I completely missing the point?

karim79
Yea, that makes sense, it's a hard question to phrase. My problem is that I would like to register an AJAX event handler that is local to an element. So if I have <div id="main"></div>, I need a non global event that fires when I do $('#main').load('bla.html') for handlers registered to $('#main') only.
Eric Coutu
A: 

Bind a global event handler to AJAX requests and then use the event target member to decide to show elements:

$(document).ajaxSuccess(function (event, xhr, settings) {
    if ($(event.target).is('#main'))
        $('#main').show();
});

Would be nice to be able to fire on AJAX requests that only target specific elements, but there doesn't seem to be a way.

EDIT: Syntax

Eric Coutu