var User = Backbone.Model.extend({
urlRoot: '/users'
});
var Users = Backbone.Collection.extend({
url: '/users'
});
var UserListView = Backbone.View.extend({ el: '.page', render: function () { var that = this; var users = new Users(); users.fetch({ success: function (users) { var template = _.template( $('#user-list-template').html(), {users: users.models}
); that.$el.html(template); } }) } });
var UserEditView = Backbone.View.extend({
el: '.page',
events: {
'submit .edit-user-form': 'saveUser',
'click .delete': 'deleteUser'
},
saveUser: function (ev) {
var userDetails = $(ev.currentTarget).serializeObject();
var user = new User();
user.save(userDetails, {
success: function (user) {
router.navigate('', {trigger:true});
}
});
}
});
<script type="text/template" id="user-list-template">
<a href="#/new" class="btn btn-primary">New</a>
<hr />
<table class="table striped">
<thead>
<tr>
<th>First Name</th><th>Last Name</th><th>Age</th><th></th>
</tr>
</thead>
<tbody>
<% _.each(users, function(user) { %>
<tr>
<td><%= htmlEncode(user.get('firstname')) %></td>
<td><%= htmlEncode(user.get('lastname')) %></td>
<td><%= htmlEncode(user.get('age')) %></td>
<td><a class="btn" href="#/edit/<%= user.id %>">Edit</a></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
var Router = Backbone.Router.extend({
routes: {
"": "home",
"edit/:id": "edit",
"new": "edit",
}
});
Root
├── imgs
├── css
│ └── style.css
├── templates
│ ├── projects
│ │ ├── list.html
│ │ └── edit.html
│ └── users
│ ├── list.html
│ └── edit.html
├── js
│ ├── libs
│ │ ├── jquery
│ │ │ ├── jquery.min.js
│ │ ├── backbone
│ │ │ ├── backbone.min.js
│ │ └── underscore
│ │ │ ├── underscore.min.js
│ ├── models
│ │ ├── users.js
│ │ └── projects.js
│ ├── collections
│ │ ├── users.js
│ │ └── projects.js
│ ├── views
│ │ ├── projects
│ │ │ ├── list.js
│ │ │ └── edit.js
│ │ └── users
│ │ ├── list.js
│ │ └── edit.js
│ ├── router.js
│ ├── app.js //Initialize the router
│ ├── main.js
│ ├── order.js //Require.js plugin
│ └── text.js //Require.js plugin
└── index.html
define([ 'jquery', 'underscore', 'backbone', // Using the text! plugin for Require.js, // we can load templates as plain text 'text!templates/project/list.html'
], function($, _, Backbone, projectListTemplate){ var ProjectListView = Backbone.View.extend({ el: $('#container'), render: function(){ // Compile the template with underscore // and add the template to the view element var data = {}; var compiledTemplate = _.template(projectListTemplate, data); this.$el.append(compiledTemplate); } }); return ProjectListView; // Return the view });