20 ms·
Something I haven't been able to understand: why does almost every Backbone project generate and update views by applying templates to generate new HTML strings
by kpozin 14y ago
Something I haven't been able to understand: why does almost every Backbone project generate and update views by applying templates to generate new HTML strings, and then new DOM fragments?
Wouldn't it be much more efficient to create a view just once by setting innerHTML, and then update it using the DOM (setting attributes, classes, innerText, etc.)? Surely this would reduce GC pressure, reflow events, and so on.
I'm seeing "use templates for everything" in most Backbone tutorials and projects, and I can't help but think that this is an anti-pattern.
- ianstormtaylor 14y agoI think one of the biggest reasons this is hard to do is because you end up having the same logic in two places. You have to keep the initial $.html() and the incremental changes consistent. Or you could have the incremental changes follow the first call t $.html(), but then you always have to add those in each render and it gets ugly there too. If you have other ideas though I'd love to hear 'em.
- kpozin 14y agoThe second of those is exactly the approach I've taken in the couple client-side web apps that I've built. I initially generate and insert generic DOM fragments from templates, but only use the template to fill in values that I know will not change throughout the lifetime of the view (the "templates" often don't have parameters). After that, I use one code path both for the initial value setting and for subsequent updates. If I'm not mistaken, this is more or less the approach used in Knockout and AngularJS.
- jashkenas 14y ago> Wouldn't it be much more efficient to create a view just > once by setting innerHTML, and then update it using the > DOM (setting attributes, classes, innerText, etc.)? Funnily enough, it usually isn't. Especially in older browsers, where performance matters most -- setting a single innerHTML call with a bunch of HTML is far cheaper than doing the equivalent number of DOM-twiddling operations. While it's entirely possible with Backbone views to listen to specific change events and only modify the smallest possible portion of the DOM, it's usually not worth the bother -- appropriately coarse-grained template renders are both more convenient and faster.