Created
February 4, 2015 00:08
-
-
Save ghing/a3df5cec5eabb68708a0 to your computer and use it in GitHub Desktop.
Template rendering views in Backbone
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
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]; | |
}, | |
// ... | |
}; |
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
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