So I am putting together a very simple app and have got a bit stuck.
So far I have my router
var AppRouter = Backbone.Router.extend({
routes:{
"":"home"
},
initialize:function () {
// Handle back button throughout the application
$('.back').live('click', function(event) {
window.history.back();
return false;
});
this.firstPage = true;
this.products = new Products();
},
home:function () {
var view = new HomeView({collection:this.products});
// render the view when the collection is loaded
this.products.on("renderCompleted:Products", function() {
//alert("ff");
view.render();
});
// fetch should trigger "reset" when complete
this.products.fetch();
}
my model
var Product=Backbone.Model.extend({
defaults:{
id:"",
name:'',
longName:'',
productID:''
}
});
return Product;
my collection
var Products=Backbone.Collection.extend({
// Book is the model of the collection
model:Product,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
var jqxhr = $.getJSON("data/product.json")
.success(function(data, status, xhr) {
$.each(data.data.productTypeList, function(i,item){
tmpItem=new Product({id:item.id,name:item.name,longName:item.longName, productID:i});
self.add(tmpItem);
});
self.trigger("fetchCompleted:Products");
})
}
});
return Products;
and my view
var HomeView = Backbone.View.extend({
template: _.template(homeViewTemplate),
render:function (eventName) {
//$(this.el).html(this.template());
this.$el.empty();
//compile template using the data fetched by collection
this.$el.append(this.template({data:this.collection.toJSON()}));
console.log("test" + this.collection.get('data'));
return this;
}
the homeViewTemplate call has this HTML
<ul >
<% for (var i = 0; i < data.length; i++) { %>
<% var item = data[i]; %>
<li>
<a href="#products/list/<%= item.productID%>"><%= item.longName %></a>
</li>
<% } %>
</ul>
you can see from the router that on init this.Products is created of the collection
then when home is called it runs the view.
I dont think anything is passed from the collection to the view though and I am not sure how this is done? Is my collection setup wrong? – do I have to call fetch and pass that to the view?
Any help is appreciated
thanks
You have to call fetch, and have its success callback trigger
view.render. You could do that using thesuccessoption of the JQuery call; or using theresetevent, whichcollection.fetchnormally calls. I’d suggest puttingcollection.resetinside your customfetch:And then in the “home” route, call
fetchand then callrenderon the callback: