0

I know you can't use the load event with the delegate function however I was wondering if there is a hack to produce a similar effect? I want to use the "data-role='table'" attribute to identify all tables that need AJAX loading and initialise the request.

<script type="text/javascript">
$(document).delegate( "table[data-role='table']", "load", function(e) {
    //load AJAX Table
});
</script>

<table data-role="table" class="table-striped">
    ...
</table>

The code is also available on jsfiddle

Note: I need to use delegate as additional tables may get added at run time (after $(document).ready)

Levi Putna
  • 2,863
  • 6
  • 30
  • 47
  • Are you trying to load external content into the tables or are you trying to attach some behavior to the `load` event? – m90 Apr 16 '12 at 09:19
  • I am trying to attach a behaviour to the load event that will load external data into the table, I know how to load the data i'm just looking for a better way of make the request. The .delegate() function was so attractive as it would work even if the table was added to the dom after document.ready had run. – Levi Putna Apr 16 '12 at 13:14

2 Answers2

0

Just a suggestion off the top of my head, but what about something like:

$(function() { // document.ready shortcut
    $("[data-role=table]").each(function(x, item) { // for each element which has this attribute.
         // identify which actual table this is (using .index() perhaps, or by id or classname)
         // call ajax to get stuff
         // load it into the relevant place
    }); 
}

More of a concept than a working solution. Hope it helps.

SpaceBison
  • 3,704
  • 1
  • 30
  • 44
  • Thanks that is similar to what I am currently doing. The problem is that will only get called once on document.ready, if a table is added via ajax I will need to run the script again. not a big problem i'm just looking for a better solution. – Levi Putna Apr 16 '12 at 12:28
  • In that case you need some kind of DOM listener, livequery exists already but it's performance degrades badly. It would be unlikely to perform badly for your needs though. You could also check out mutation-events, there's an SO post here: http://stackoverflow.com/questions/1091661/detect-element-content-changes-with-jquery – SpaceBison Apr 16 '12 at 12:38
0

Webkit throws a few DOM mutation events, but I think those are even depreciated.

It's getting a bit old now, but .livequery (http://docs.jquery.com/Plugins/livequery) is still the best option I know of. You can use:

$("[data-roll=table]").livequery(function() {
     ...
});

should fire that callback whenever a new element matching your selector is added to the page.

nicholas
  • 14,184
  • 22
  • 82
  • 138