I'm trying to make a JSON call and list the items in it with backbone. I get the items back successfully and am able to confirm they are available with a console log, but when I try passing them into my template I'm getting an error saying
"Uncaught ReferenceError: quotes is not defined"
My code:
var Quotes = Backbone.Collection.extend({
url: '/quotes.json'
});
var UserListView = Backbone.View.extend({
el: '.quote-list',
render: function() {
var that = this;
var quotes = new Quotes();
quotes.fetch({
success: function(quotes) {
var variables = {
search: "search"
};
var template = _.template($('#quotes-template').html(), variables);
console.log(template)
that.$el.html(template);
}
})
}
});
var Router = Backbone.Router.extend({
routes: {
"": "home"
}
});
$(document).ready(function() {
var userListView = new UserListView;
var router = new Router;
router.on('route:home', function() {
//render user list
userListView.render();
});
Backbone.history.start();
})
<body>
<div class="quote-list"></div>
<script type="text/template" id="quotes-template">
<% _.each(quotes, function(quote) { %>
<ul>
<li>
<%=quote.source %>
</li>
<li>
<%=quote.context %>
</li>
</ul>
<% }); %>
</script>
<script src="js/app.js"></script>
</body>
You are using variable quotes
in the underscore template, but the data you're passing to _.template()
does not contain quotes
.
Your code should be:
quotes.fetch({
/*---------------collection----------------*/
/*-------------------v----------------*/
success: function(quotes, response, options) {
var variables = {
search: "search"
}; // ...?
var template = _.template($('#quotes-template').html(), {
quotes: quotes
});
that.$el.html(template);
}
});
Since the first argument quotes
in your success callback is a Backbone.Collection
, you might also want to change the template as follows, else you can pass the second argument, which is the actual response to _.templte()
.
<body>
<div class="quote-list"></div>
<script type="text/template" id="quotes-template">
<% _.each(quotes.models, function(quote) { %>
<ul>
<li>
<%=quote.get("source") %>
</li>
<li>
<%=quote.get("context") %>
</li>
</ul>
<% }); %>
</script>
<script src="js/app.js"></script>
</body>