Created
July 9, 2013 11:53
-
-
Save fantactuka/5956782 to your computer and use it in GitHub Desktop.
Template-level defined views in a backbone-ish app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Handlebars helper | |
| var ViewsCache = Backbone.View.ViewsCache = {}; | |
| Handlebars.registerHelper('view', function(view, options) { | |
| var id = _.uniqueId('view-'); | |
| views[id] = { view: view, options: options.hash }; | |
| return new Handlebars.SafeString('<script type="text/view" data-view-id="' + id + '"></script>'); | |
| }); | |
| // Base view class | |
| Backbone.View.prototype.render = function() { | |
| // .. view rendering logic .. | |
| // Template-level defined sub-views | |
| this.subViews = {}; | |
| _.each(this.$el.find('script[type="text/view"]'), function(element) { | |
| var $element = $(element), | |
| viewId = $element.data('view-id'), | |
| config = Backbone.View.ViewCache[viewId], | |
| View = require(config.view), | |
| view = new View(config.options); | |
| view.render(); | |
| $element.replaceWith(view.$el); | |
| this.subViews[viewId] = view; | |
| }, this); | |
| }; | |
| Backbone.View.prototype.destroy = function() { | |
| // Default view destroying functionality ... | |
| // Destroying sub views | |
| _.each(this.subViews, function(view) { | |
| view.destroy(); | |
| }); | |
| this.subViews = null; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment