Skip to content

Instantly share code, notes, and snippets.

@ghing
Created February 4, 2015 00:08
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 ghing/a3df5cec5eabb68708a0 to your computer and use it in GitHub Desktop.
Save ghing/a3df5cec5eabb68708a0 to your computer and use it in GitHub Desktop.
Template rendering views in Backbone
var BaseView = Backbone.View.extend({
children: {},
checkId: null,
shown: false,
events: {
'click .back-to-top': 'backToTop',
'click h2 a': 'jumpTo'
},
constructor: function(options) {
this.options = this.options || {};
_.extend(this.options, { animationLength: 500, offset: 100}, options);
Backbone.View.apply(this, arguments);
},
/**
* Compile templates and store them in a lookup table
*/
initializeTemplates: function() {
var sources;
this._templates = {};
// No template sources
if (!this.options.templateSource) {
return this;
}
if (!_.isObject(this.options.templateSource)) {
sources = {
'_default': this.options.templateSource
};
}
else {
sources = this.options.templateSource;
}
_.each(sources, function(source, name) {
this._templates[name] = this.compileTemplate(source);
}, this);
},
/**
* Compile a template source in a string into a template object.
*/
compileTemplate: function(templateSource) {
return _.template(templateSource);
},
/**
* Get a pre-compiled template.
*/
getTemplate: function(name) {
name = name || '_default';
return this._templates[name];
},
// ...
};
var ChildView = BaseView.extend({
options: {
templateSource: {
'_default': $('#filter-template').html(),
'candidate': '<p><strong><%= name %></strong>:<br><%= race %></p>'
}
},
initialize: function(options) {
// Stuff ...
this.initializeTemplates();
// More stuff ...
},
// ...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment