Skip to content

Instantly share code, notes, and snippets.

@ghing

ghing/BaseView.js

Created Feb 4, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.