Skip to content

Instantly share code, notes, and snippets.

@fantactuka
Created July 9, 2013 11:53
Show Gist options
  • Save fantactuka/5956782 to your computer and use it in GitHub Desktop.
Save fantactuka/5956782 to your computer and use it in GitHub Desktop.
Template-level defined views in a backbone-ish app
// 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;
};
<div class="page-header"> ... </div>
{{view "views/dashboard/index-view" model=model amount=3}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment