Skip to content

Instantly share code, notes, and snippets.

@mparke
Created August 2, 2013 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mparke/6142590 to your computer and use it in GitHub Desktop.
Save mparke/6142590 to your computer and use it in GitHub Desktop.
Backbone base view with Handlebars template rendering and nested view support.
App.Views.Base = Backbone.View.extend({
templateName: null,
model: null,
render: function(options){
var data;
if(this.templateName !== null){
if(this.model !== null){
data = this.model.toJSON()
}else{
data = {}
}
this.$el.html(Handlebars.templates[this.templateName](data))
}
this.renderNested();
return this.$el;
},
renderNested: function() {
var me = this,
config, options;
if(this.nested){
_.each(this.nested, function(config, viewName, nested){
options = config.options;
// instantiate model definition if provided
if(options.model){
options.model = new options.model();
}
// instantiate the view instance with options
me[viewName] = new config.constructor(options);
// render the view to the target
me.$el.find(config.target).html(me[viewName].render());
// register events in the nested view
_.each(config.events, function(callbackName, eventName, list){
me[viewName].on(eventName, me[callbackName], me);
});
});
}
}
});
// A nested view configuration example
var TopLevel = Backbone.View.extend({
tagName: 'div'
nested: {
form: {
target: '.form-container',
constructor: Views.Form,
options: {
model: Models.Form
},
// events we want registered on the nested view,
// and handled on this view
events: {
'submit': 'onSubmit'
}
}
},
onSubmit: function(){}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment