Skip to content

Instantly share code, notes, and snippets.

@flengyel
Created August 7, 2013 16:16
Show Gist options
  • Save flengyel/6175577 to your computer and use it in GitHub Desktop.
Save flengyel/6175577 to your computer and use it in GitHub Desktop.
Worked examples derived from Chapter 2 of Building Backbone Plugins.
<!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">
BBPlug = {};
BBPlug.BaseView = Backbone.View.extend({
render: function () {
var data;
if (this.serializeData) {
data = this.serializeData();
};
var renderedHtml = _.template(this.template, data);
this.$el.html(renderedHtml);
if (this.onRender) {
this.onRender();
}
}
});
var template = "<h1>Hello World!</h1>";
HelloWorldView = BBPlug.BaseView.extend({
el: "#div",
template: template
});
var view = new HelloWorldView();
view.render();
console.log(view.$el);
BBPlug.ModelView = BBPlug.BaseView.extend({
serializeData: function() {
var data;
if (this.model) {
data = this.model.toJSON(); // serialize means JSONification
}
return data;
}
});
var model = new Backbone.Model({
message: "Hello Data-World!"
});
var template = "<h2><%= message %></h2>";
// Extend ModelView to include el: and template:
BBPlug.TemplateModelView = BBPlug.ModelView.extend({
el: "#div1",
template: template,
});
// Question: why must the el: and template: properties
// be defined by extending the ModelView object? If
// added to the constructor, the model message cannot be found.
// note connection between model and view
var view = new BBPlug.TemplateModelView({
model: model
});
view.render();
console.log(view.$el);
// generalize to collections
BBPlug.CollectionView = BBPlug.BaseView.extend({
serializeData: function() {
return {
items: this.collection.toJSON() // serialize means JSONification
};
}
});
var collection = new Backbone.Collection([
{message: "Hello"},
{message: "Collection"},
{message: "World"}
]);
var template = "<h3><% _.each(items, function(item){ %><%= item.message %> <% })%>!</h3>";
// Once again, we have to extend CollectionView to include the template
BBPlug.TemplateCollectionView = BBPlug.CollectionView.extend({
el: "#div2",
template: template
});
// The collection can be included in the constructor, but not the template!
// note connection between collection and view
var view = new BBPlug.TemplateCollectionView({
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