In order to write
backbone.js application we need following libraries.
- jquery.js
- underscore.js
- backbone.js
Lets create main.js and
index.html.
Our index.html file is
as follows:
<html>
<head>
<head>
<title>Backbone.js tutorial</title>
</head>
<body>
<div
class="personDetail"></div>
<script
type="text/template" id="templateId">
<ul>
<li>Name:
<%=name%></li>
<li>Address:
<%=address%></li>
<li>Age:
<%=age%></li>
<li>Occupation:
<%=occupation%></li>
</ul>
</script>
<script
type="text/javascript" src="jquery.js"></script>
<script
type="text/javascript" src="underscore.js"></script>
<script
type="text/javascript" src="backbone.js"></script>
<script
type="text/javascript" src="main.js"></script>
</body>
</html>
Now lets modify our
main.js
var Person =
Backbone.Model.extend({
defaults:{
name:”kamal
pandey”,
age:27,
adderss:”tamghas-1,
gulmi, Nepal”,
job:”software
developer”
},
initialize:function(){
console.log(“model
has been initialized”);
}
});
In the above, we simply
define the class with some default values like name, age, address and
job.
It also contains the
initialize function that is called as soon as the model is
initialized.
var person = new
Person(); //creating a new object
By using the get method
we can get the name, age, address and job.
So, person.get('name'); // will give kamal pandey
person.get('age'); //
will give 27 and so on.
Getting the attribute
of the model is quite straightforward. So is setting the value. We
can simply do
person.set('name',
'Rajeev Pandey') ; // update the name
person.set('age',19); and so on.
We can even set all the
attributes at once using
person.set({
name:”Rajeev
Pandey”,
address:”kathmandu
Nepal”,
age:19,
job:”teacher”
});
So we learned about the
model lets proceed with the views. View means how we represent data.
var PersonView =
Backbone.View.extend({
el:”.personDetail”,
template:_.template($(“#templateId”).html()),
initialize:function(){
this.render();
},
render:function(){
this.$el.html(this.template(this.model.toJSON()));
}
});
var person = new
Person();
var personView = new
PersonView({
model:person
});