Note that there are some explanatory texts on larger screens.

plurals
  1. PORendering Backbone view using document fragment breaks event handling
    primarykey
    data
    text
    <p>I modified my Backbone app to render a large table using a DOM document fragment, which results in a nice performance improvement when there are many rows.</p> <p>Unfortunately, this seems to break event handling, so that the views for each row no longer receive click events. I created a <a href="http://jsfiddle.net/HAZ4G/1/" rel="nofollow">minimal example</a> to demonstrate this.</p> <p>What do I have to do to fix this?</p> <pre><code>// Javascript $(window).load(function(){ var Item = Backbone.Model.extend(); var Items = Backbone.Collection.extend({ model: Item, count: 5, initialize: function() { for(i=0; i&lt;this.count; i++){ this.add(new Item({text: i})); } } }); var ItemView = Backbone.View.extend({ tagName: 'tr', initialize: function(item) { this.item = item; }, render: function() { this.$el.append('&lt;td class="item"&gt;' + this.item.get('text') + '&lt;/td&gt;'); return this; }, events: function() { return { "click .item": function() { console.log('handling click on item '+this.item.get('text')); } }; } }); var TableBodyView = Backbone.View.extend({ tagName: 'tbody', render: function() { if(this.options.useFragment){ this.renderWithFragment(); } else { this.renderWithoutFragment(); } return this; }, renderWithFragment: function() { var fragment = document.createDocumentFragment(); this.collection.each(function(item){ fragment.appendChild((new ItemView(item)).render().el); }); this.$el.append(fragment.cloneNode(true)); }, renderWithoutFragment: function() { self = this; this.collection.each(function(item){ self.$el.append((new ItemView(item)).render().el); }); } }); var items = new Items(); $('#t1').append((new TableBodyView({collection: items, useFragment: false})).render().el); $('#t2').append((new TableBodyView({collection: items, useFragment: true})).render().el); }); // HTML &lt;table id="t1" /&gt; &lt;table id="t2" /&gt; // CSS table { float: left; margin: 10px; padding: 5px; } table#t1 { background: green; } table#t2 { background: red; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload