Backbone.js Application Walkthrough Part 3: New View and External Templating – Video Tutorial

Moving on to part 3 of the Backbone Application Walkthrough video series, we work on moving all of the templates to external files to reduce the dependency on the templates being included in the index.html file and so that they might become available if we use these views on different pages. Also, I added an extra view that wasn’t in the original application because, as you’ll see in the video, it makes things a little nicer.

Backbone.js Video Tutorial Series

JavaScript Code

I’ll just post some of the code on here because it isn’t really worth posting all of it. The first line tells you which file it is.

"js/views/start.js"
1
2
3
4
5
6
7
8
9
10
11
12
13
window.StartView = Backbone.View.extend({

initialize: function() {
this.template = _.template( tpl.get('start-template') );
},

render: function() {
this.$el.html( this.template() );

return this.el;
}

});
"js/util.js"
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
28
29
30
31
32
33
34
35
tpl = {

// Hash of preloaded templates for the app
templates:{},

// Recursively pre-load all the templates for the app.
// This implementation should be changed in a production environment. All the template files should be
// concatenated in a single file.
loadTemplates:function (names, callback) {

var that = this;

var loadTemplate = function (index) {
var name = names[index];
console.log('Loading template: ' + name);
$.get('templates/' + name + '.html', function (data) {
that.templates[name] = data;
index++;
if (index < names.length) {
loadTemplate(index);
} else {
callback();
}
});
}

loadTemplate(0);
},

// Get template by name from hash of preloaded templates
get:function (name) {
return this.templates[name];
}

};
"js/main.js"
1
2
3
4
5
6
7
8
9
10
11
12
Backbone.View.prototype.close = function () {
console.log('Closing view ' + this);
if (this.beforeClose) {
this.beforeClose();
}
this.remove();
this.unbind();
};

tpl.loadTemplates(['header', 'wine-details', 'wine-list-item', 'start'], function () {
... // Run App
});

Backbone.js Video Tutorial Series

Looking Ahead

As I stated in the video, there should be 2 more video left in this series. The next one will be finishing up the application and getting it running. The one after that will be more of a RequireJS tutorial than anything, but will show you how to make your Backbone applications work with AMD. Part 4 should be out this Thursday, so look forward to that. God bless and happy coding!

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.