I have edited this question because people are pointing me to this link:-
uncaught TypeError: Cannot call method 'replace' of undefined backbone.js
But I think these two questions are different, also the solution provided there is already implemented here. People also mentioned that the code is working on their end, if you are executing this code on your machine then please click on the Home Page link and let me know if the Home Page view is loading in your end.
Actual Question
I am new to Backbone.js and currently going through the tutorials. I see that different developers use different ways to accomplish a task, so I tried to mix match their approaches to understand it in more depth and have a clear concept. What I am trying to achieve here in my code is to perform switch view using a Router, and this is how my code looks (I have trimmed it down to the basics so that it easy to debug) -
<script type="text/template" id="home-template">
<h1>This is the home page</h1>
</script>
<script type="text/javascript">
var HomeView = Backbone.View.extend({
tagName: 'div',
initialize: function() {
$("body").html(this.el);
this.template = _.template($('#home-template').html());
this.render();
},
render: function() {
this.$el.html(this.template());
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'home': 'home'
},
home: function() {
this.view = new HomeView();
}
});
var appRouter = new AppRouter();
Backbone.history.start();
</script>
<a href = "#/home">Home Page</a> <br />
So when I am loading the page it is loading correctly, but when I am clicking on the Home Page link, it is getting a JS error in the line -
this.template = _.template($('#home-template').html());
I have also added a screenshot of the problem that I am facing. I went through the solutions given in stackoverflow for this kind of error and also modified my code according to the changes suggested, but it didn't work. The issue is, the _.template function is not able to identify the home-template template. Any idea why is it so and how to resolve it?
$("body").html(this.el);does not do whatever you thought it does. You must remove that.What this does is replace the HTML of the element named
bodywith the value ofthis.el. When you replace the contents ofbody, you also erase all yourscriptelements and thus$('#home-template').html()fails to find an element with idhome-templateand returns the resultundefinedwhich causes a failure later when you try to use your template.In order to give a element to which your view will be attached, you can create an element for it in the HTML:
And pass it to your view when you create it, or pass a CSS selector: