Introduction to Backbone.js Part 2: Views - Video Tutorial

Last week you saw a video tutorial on using Models in Backbone.js. This week we’ve moved right along to part 2: learning about Views in Backbone.js. As usual, Backbone.js has made things super simple, yet you get a lot for how little code you write. You’ll see how to attach events (super easy) and utilize models (also super easy) to give your views some data to work with.

Backbone.js Video Tutorial Series

Final HTML Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Learning About Backbone.js Views</title>
<style type="text/css">
#container { padding:20px; border:1px solid #333; width:400px; }
#list-template { display:none; }
</style>
</head>
<body>

<div id="container">
<button>Load</button>
<ul id="list">
</ul>
</div>

<div id="list-template">
<li><a href=""></a></li>
</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
</body>
</html>

Final JavaScript Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
model = new Backbone.Model({
data:[
{ text: "Google", href: "http://google.com" },
{ text: "Facebook", href: "http://facebook.com" },
{ text: "Youtube", href: "http://youtube.com" }
]
});

var View = Backbone.View.extend({
initialize: function () {
this.template = $('#list-template').children();
},
el: '#container',
events: {
"click button": "render"
},
render: function() {
var data = this.model.get('data');

for (var i=0, l=data.length; i<l; i++) {
var li = this.template.clone().find('a').attr('href', data[i].href).text(data[i].text).end();
this.$el.find('ul').append(li);
}
}
});

var view = new View({ model: model });

Conclusion

Judging by comments posted on the introductory post to these tutorials, people seem to be anxious to see the entire series, so I’ve decided that both of next week’s posts will be continuing this series with more video tutorials. Then I’ll take a break for either one post or two before walking you through a full Backbone.js app.

Backbone.js Video Tutorial Series

Author: Joe Zimmerman

Author: Joe Zimmerman Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.