Backbone SubView Demo
Simple example of Backbone view with subview
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.14/backbone.localStorage-min.js"></script>
<body>
<div id="application">
<p>Add a user to the user list</p>
<div id="login"></div>
<ul id="online-users"></ul>
</div>
<script id="login-template" type="text/template">
<h1>login</h1>
<input id="username" type="text" placeholder="username"/>
<input id = "email" type = "text" placeholder = "email" />
<button id = "button-login" type = "button" > Login </button>
</script>
<script id="userlist-template" type="text/template">
<li>
<span> <%= username %> / <%= email %></span>
<button id = "force-logout"> force logout </button>
</li>
</script>
CSS
#force-logout {
margin-left: 20px;
float: right;
}
#online-users {
margin-top: 15px;
}
ul {
padding: 0;
margin: 0;
}
ul li {
display: block;
width: 300px;
}
JavaScript
var app = app || {};
app.User = Backbone.Model.extend({
defaults: {
username: '',
email: ''
}
});
app.UserList = Backbone.Collection.extend({
model: app.User,
localStorage: new Backbone.LocalStorage('user-backbone')
});
app.AppView = Backbone.View.extend({
el: '#application',
initialize: function () {
this.users = new app.UserList();
this.loginView = new app.LoginView();
this.userListView = new app.UserListView({
collection: this.users
});
this.listenTo(this.loginView, 'login', this.login);
},
render: function () {
this.loginView.setElement(this.$('#login')).render();
this.userListView.setElement(this.$('#online-users')).render();
},
start: function () {
this.render();
this.users.fetch();
},
login: function (user) {
this.users.create(user);
}
});
app.LoginView = Backbone.View.extend({
template: _.template($('#login-template').html()),
events: {
'click #button-login': 'login'
},
render: function () {
this.$el.html(this.template());
},
login: function () {
var username = this.$('#username').val().trim();
var email = this.$('#email').val().trim();
this.trigger('login', {
username: username,
email: email
});
this.clearForm();
},
clearForm: function () {
this.$('#username').val('');
this.$('#email').val('');
}
});
app.UserListView = Backbone.View.extend({
initialize: function () {
this.listenTo(this.collection, 'add', this.renderOne);
this.listenTo(this.collection, 'reset', this.renderAll);
},
render: function () {
this.renderAll();
},
renderOne: function (user) {
var view = new app.UserView({
model: user
});
this.$el.append(view.render().el);
},
renderAll: function () {
...