9 ms·
Here's what we did: 1) Derive all views from our own BaseView class (which derives from Backbone.View) 2) BaseView's initialize function sets $el.data('view',
by snprbob86 15y ago
Here's what we did:
1) Derive all views from our own BaseView class (which derives from Backbone.View)
2) BaseView's initialize function sets $el.data('view', this)
3) BaseView provides a `dispose` method which with some default logic for event handlers added in a particular way.
4) We overrode jQuery.cleanData to check for the view data on each element and call dispose on them. This ensures every view is cleaned up when it is removed from the DOM via jQuery.
5) Use $.fn.remove and $.fn.detach appropriately.
This works splendidly in practice.
- sgk284 15y agoI'm snprbob86's co-founder at Thinkfuse. Here's our actual jQuery cleanData wrapper (in coffeescript): https://gist.github.com/2046371 https://gist.github.com/2046371 jQuery.cleanData = _.wrap jQuery.cleanData, (cleanData, elems) -> for elem in elems $(elem).data('view')?.dispose() cleanData.apply @, arguments That lets jQuery handle garbage collecting automatically for us whenever the Backbone view's corresponding element is removed from the page. Just make sure your base view constructor sets the 'view' data attribute on it's element.
- funkah 15y ago> initialize function sets $el.data('view', this) Whoa, you can do that? Huh.