Hacker News new | past | comments | ask | show | jobs | submit login

A HUGE difference, performance-wise. Delegation is O(1), while using any form of `each()` is going to be O(n).

To elaborate -- jQuery does not set an event-handler for each TR -- it sets one on the parent element (the table), and basically when the table is clicked jQuery gets the event and asks: "are you a TR?", and if so, then the handler is called with the clicked element as the context. So even if your table has 1million rows, only 1 event handler is attached and the DOM is only accessed once.

Of course, accessing the DOM 1 million times within a loop is going to take forever.




That's certainly true, but for what kind of use case do you need 1 million rows? It think that 1000 is already a lot, and if you exceed this, maybe it's better to design the app in a way that you need fewer rows...


It's not just for large numbers of elements. If you have dynamic elements that get added/removed you can define a single event handler on the parent with a filter condition on it's children that handles them all.

The following CoffeeScript event handler would be fired for every table cell with the foobar class that is a child of #myTable:

    $('#myTable').on 'click', 'td.foobar', () ->
        # Do something
What's great here is I can add/remove rows to the table without binding/unbinding event handlers. We use this a lot in our app (http://www.jackdb.com/). The main app content is a single page with all content dynamically loaded and added/removed on the fly. If we had to add event handlers for each data cell (or even row) there would be 1000s of them.


That's not how I would do it in Minified. I'd rather set up the event handler when creating the table row, one at a time, using the element factory (EE() or clone()) onCreate handler. Because otherwise you'd have to store data in the DOM model, which IMHO is not a very elegant design. But it's certainly faster or at least easier on memory consumption if you have many thousand rows.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: