Skip to content

Instantly share code, notes, and snippets.

@scottcorgan
Created August 8, 2012 17:35
Show Gist options
  • Save scottcorgan/3296918 to your computer and use it in GitHub Desktop.
Save scottcorgan/3296918 to your computer and use it in GitHub Desktop.
Backbone View in a Requirejs Module
define(
[
// Dependencies
'text!someTemplate.html'
],
function(someTemplateTpl){
return Backbone.View.extend({
// Set the id if you are creating this element from scratch
// If the element already exists, use el: '#someView' to
// associate this view with that element
id: 'someView',
events: {
'click': 'doSomething'
},
initialize: function(){
// Make sure that all functions called in this view
// have the context pointing back to this view
_.bindAll(this);
// Defaults and object values go here
this.template = '';
},
render: function(){
// Compile our template with our model info
// The model will be injected into this view or
// instantiated in this view
this.template = Mustache.render(someTemplateTpl, {
model: this.model.toJSON()
});
// Add the template into the wrapper of this view (<div id='#someView'></div>)
this.$el.append(this.template);
// Return the jQuery object of the element so this is chainable
return this.$el;
},
doSomething: function(e){
// Some this form moving on if this is a link clicked
e.preventDefault();
// do something when it's clicked, here
}
});
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment