JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/template" id="data-template">
<%= data %> //make sure you have a key called data on your model
</script>
<div id="app-container">
<ul id="data-list"></ul>
</div>
JavaScript
var app = {};
app.DataView = Backbone.View.extend({
//I call it template string for clarification
templateString : $("#data-template").html(),
initialize: function () {
console.log("creating a data view with tag " + this.model.get("tag"));
},
render: function () {
//we let underscore merge the data and the template
var createdElement = _.template(this.templateString, this.model.toJSON());
//Backbone creates a $el upon initialization of the view
//the el is created from the tagName, className (if given) and id (if given)
//which you have passed in the constructor
//the this element we append (by using jquery) the element we just created by
//inserting the content in the template
this.$el.append(createdElement);
return this;
}
});
app.AppView = Backbone.View.extend({
//el: "#htmldataapp", we pass the element reference in the constructor but we could set the reference here as well hard coded.
initialize: function () {
//rather use listenTo (less risky for memory leaks)
//app.datamodels.on('reset', this.addAll, this);
this.listenTo(this.model, 'reset', this.render);
},
addOne: function (datamodel) {
//can be removed
},
addAll: function () {
//can be removed
},
//render is called by the framework when the collection is reset (see below)
render: function () {
//for each model we create a child view, whihc is a data view.
this.model.each(function (model) {
this.$el.append(new app.DataView({
model: model,
//tell backbone what kind of element it should create.
//without the tag property on the model,
//we could strip the element from the string
//and use that here, but this is way cleaner.
tagName: model.get("tag")
}).render().el);
...