views:

768

answers:

3

So, you have a page:

<html><head>
<script type="text/javascript" src="jquery.1.3.2.js"></script>
<script type="text/javascript">
$(function() {
  var onajax = function(e) { alert($(e.target).text()); };
  var onclick = function(e) { $(e.target).load('foobar'); };
  $('#a,#b').ajaxStart(onajax).click(onclick);
});
</script></head><body>
<div id="a">foo</div>
<div id="b">bar</div>
</body></html>

Would you expect one alert or two when you clicked on 'foo'? I would expect just one, but i get two. Why does one event have multiple targets? This sure seems to violate the principle of least surprise. Am i missing something? Is there a way to distinguish, via the event object which div the load() call was made upon? That would sure be helpful...

EDIT: to clarify, the click stuff is just for the demo. having a non-generic ajaxStart handler is my goal. i want div#a to do one thing when it is the subject of an ajax event and div#b to do something different. so, fundamentally, i want to be able to tell which div the load() was called upon when i catch an ajax event. i'm beginning to think it's not possible. perhaps i should take this up with jquery-dev...

A: 

Because you have a selector with two elements, you're creating two ajaxStart handlers. ajaxStart is a global event, so as soon as you fire any ajax event, the onajax function is going to be called twice. So yes, you'd get two popups.

R. Bemrose
no. i'm not firing once for each div. try the page. you'll see two alerts and only one will have the content change.
Nathan Bubna
A: 

when you set ajaxStart, it's going to go off for both divs. so when you set each div to react to the ajaxStart event, every time ajax starts, they will both go off...

you should do something separate for each click handler and something generic for your ajaxStart event...

Jason
see my edit on the question...
Nathan Bubna
+1  A: 

Ok, i went ahead and looked at the jQuery ajax and event code. jQuery only ever triggers ajax events globally (without a target element):

jQuery.event.trigger("ajaxStart");

No other information goes along. :(

So, when the trigger method gets such call, it looks through jQuery.cache and finds all elements that have a handler bound for that event type and jQuery.event.trigger again, but this time with that element as the target.

So, it's exactly as it appears in the demo. When one actual ajax event occurs, jQuery triggers a non-bubbling event for every element to which a handler for that event is bound.

So, i suppose i have to lobby them to send more info along with that "ajaxStart" trigger when a load() call happens.

Update: Ariel committed support for this recently. It should be in jQuery 1.4 (or whatever they decide to call the next version).

Nathan Bubna
I've opened a thread on jquery-dev to try and prod discussion about a solution for this:http://groups.google.com/group/jquery-dev/browse_thread/thread/caf31f67a3ac159c
Nathan Bubna