This article explains DOM events in backbone.js. How they work in Backbone and how to create an application that listens for DOM events in backbone.js. In this tutorial we can do the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="addUser" action="">
<input type="text" placeholder="Name of the user">
<input type="submit" value="Add User">
</form>
<script id="userTemplate" type="text/template">
<span><strong><%= name %></strong> (<%= age %>) - <%= occupation %></span>
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</script>
<script src="js/underscore.js"></script>
<script src="js/jquery.js"></script>
<script src="js/backbone.js"></script>
<script src="js/app.js"></script>
</body>
</html>
(function () {
window.App = {
Models: {},
Collections: {},
Views: {}
};
window.template = function (id) {
return _.template($('#' + id).html());
};
// User Model
App.Models.User = Backbone.Model.extend({
defaults: {
name: 'New Client',
age: 28,
occupation: 'Employee'
}
});
// A List of Employee
App.Collections.Employee= Backbone.Collection.extend({
model: App.Models.User
});
// View for all employee
App.Views.Employee = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection.on('add', this.addOne, this);
},
render: function () {
this.collection.each(this.addOne, this);
return this;
},
addOne: function (user) {
var userView = new App.Views.User({ model: user});
this.$el.append(userView.render().el);
}
});
// The View for a User
App.Views.User = Backbone.View.extend({
tagName: 'li',
template: template('userTemplate'),
initialize: function () {
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
events: {
'click .edit': 'editUser',
'click .delete': 'DestroyUser'
},
editUser: function () {
var newName = prompt("Enter the new name of client", this.model.get('name'));
if (!newName) return;
this.model.set('name', newName);
},
DestroyUser: function () {
this.model.destroy();
},
remove: function () {
this.$el.remove();
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
App.Views.AddUser = Backbone.View.extend({
el: '#addUser',
events: {
'submit': 'submit'
},
submit: function (e) {
e.preventDefault();
var newUserName = $(e.currentTarget).find('input[type=text]').val();
var user = new App.Models.User({ name: newUserName });
this.collection.add(user);
}
});
var employeeCollection = new App.Collections.Employee([
{
name: 'Smith Patel',
age: 25
},
{
name: 'Jhon farnandis',
age: 24,
occupation: '.NET Developer'
},
{
name: 'Mahak Ahuja',
age: 26,
occupation: 'Web Designer'
}
]);
var addUserView = new App.Views.AddUser({ collection: employeeCollection });
employeeView = new App.Views.Employee({ collection: employeeCollection });
$(document.body).append(employeeView.render().el);
})();