Upgrading from .live () to .on () for single-page applications

As we all know, since jQuery 1.7:

$('someSelector').live('click', fn());

became essentially:

$(document).on('click', 'someSelector', fn());

All direct events are not directly attached to the elements in the selector, but are delegated to the document.

This, I believe, is that elements that will be matched 'someSelector'in the future are not present in the DOM, so you cannot bind event handlers (using direct or delegated bindings).

For single-page applications, where the vast majority, if not all elements are dynamically loaded, recommendations are published on how to best deal with the performance problem by linking everything to the document?

Coverage, for example, is the best way to register / re-register event handlers when new content is loaded through ajax()and how to update code written in lazy .live()thinking?

+5
source share
1 answer

I am not sure if there are any “published recommendations”.

I think this approach has its merits:

  • Find the closest logical common ancestor that will not be removed from the document.

    Example. For the behavior of a row in a drag table, this will be the parent table (or tbody).

  • Tie events there. This allows you to have separate instances of the same behavior in different ways, without requiring context checking.

    . , , , , . document .

  • , document, " ", .

    . , , document ( , table.draggable tr ).

  • , , .

, , . , :

// once, beforehand
var draggableTableRowBehavior = {
  dragstart: function () { /* ... */ },
  dragstop: function () { /* ... */ }
  /* ... */
};

//in Ajax success:
$table.on(draggableTableRowBehavior, 'tr');
+3

All Articles