Created
August 2, 2013 19:17
-
-
Save mparke/6142590 to your computer and use it in GitHub Desktop.
Backbone base view with Handlebars template rendering and nested view support.
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
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