Created
December 2, 2010 18:19
-
-
Save johnreilly/725790 to your computer and use it in GitHub Desktop.
My attempt at using Backbone.js views to render other "sub-views"
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Test</title> | |
<script src="js/jquery.js" type="text/javascript"></script> | |
<script src="js/underscore.js" type="text/javascript"></script> | |
<script src="js/backbone.js" type="text/javascript"></script> | |
<script type="text/javascript" charset="utf-8"> | |
$(function(){ | |
// SubView is in charge of rendering an individual item | |
var SubView = Backbone.View.extend({ | |
initialize: function() { | |
this.template = '<div class="subview-item">Item Name: <%= name %></div>' | |
}, | |
render: function(){ | |
$(this.el).html(_.template(this.template, {name: this.model.name})); | |
return this; | |
} | |
}); | |
// MainView is in charge of rendering several items (using SubViews), plus a short summary. | |
var MainView = Backbone.View.extend({ | |
el: $('#content'), | |
initialize: function(){ | |
this.template = '<p>There are <%= model.length %> objects:</p><ul id="list"></ul>'; | |
}, | |
render: function(){ | |
//render our main view template | |
$(this.el).html(_.template(this.template, {model: this.model})); | |
//render a subview for each item in the collection | |
var mainView = this; | |
_.each(this.model, function(item){ | |
var x = new SubView({model: item, tagName: 'li'}); | |
$(mainView.el.find('#list').append(x.render().el)) | |
}); | |
return this; | |
} | |
}); | |
//build a collection of items to render | |
var item1 = {name: 'one'}; | |
var item2 = {name: 'two'}; | |
var item3 = {name: 'three'}; | |
var collection = [item1, item2, item3]; | |
// Let MainView render the collection | |
var mainView = new MainView({ | |
model: collection | |
}); | |
mainView.render(); | |
// Render an individual item using a SubView | |
var subView = new SubView({ | |
model: item2, | |
el: $('#more-content') | |
}); | |
subView.render(); | |
}); | |
</script> | |
</head> | |
<body> | |
<!-- Placeholder for our main view --> | |
<div id="content"></div> | |
<!-- Placeholder for a separate instance of a subview --> | |
<p>Now here's a single item rendered in a subview:</p> | |
<div id="more-content"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is it working?