Skip to content

Instantly share code, notes, and snippets.

@flengyel
Last active December 20, 2015 15:49
Show Gist options
  • Select an option

  • Save flengyel/6157324 to your computer and use it in GitHub Desktop.

Select an option

Save flengyel/6157324 to your computer and use it in GitHub Desktop.
Elaboration on and corrections to the BaseView object from Building Backbone Plugins. The main correction is the substitution of item.message for item in the underscore template for the CollectionView constructor. This is no criticism: the book is refreshingly to the point--the authors know their audience.
<!DOCTYPE HTML>
<HTML>
<HEAD>
<meta lang="en">
<title>Backbone BaseView with corrections</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="backbone.js"></script>
</HEAD>
<BODY>
<div id="div"></div>
<div id="div1"></div>
<div id="div2"></div>
<script type="text/javascript">
BaseView = Backbone.View.extend({
render: function () {
var data;
if (this.serializeData) {
data = this.serializeData();
};
var renderedHtml = _.template(this.template, data);
this.$el.html(renderedHtml);
}
});
var template = "<h1>Hello World!</h1>";
HelloWorldView = BaseView.extend({
el: "#div",
template: template
});
var view = new HelloWorldView();
view.render();
console.log(view.$el);
var template = "<h2><%= message %></h2>";
DataDrivenView = BaseView.extend({
el: "#div1",
template: template,
serializeData: function() {
return this.model.toJSON(); // serialize means JSONification
}
});
var model = new Backbone.Model({
message: "Hello Data-World!"
});
// note connection between model and view
var view = new DataDrivenView({
model: model
});
view.render();
console.log(view.$el);
// generalize to collections
var template = "<h3><% _.each(items, function(item){ %><%= item.message %> <% }) %>!</h3>";
CollectionView = BaseView.extend({
el: "#div2",
template: template,
serializeData: function() {
return {
items: this.collection.toJSON() // serialize means JSONification
};
}
});
var collection = new Backbone.Collection([
{message: "Hello"},
{message: "Collection"},
{message: "World"}
]);
// note connection between model and view
var view = new CollectionView({
collection: collection
});
view.render();
console.log(view.$el);
</script>
</BODY>
</HTML>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment