How to display the product details when clicked from the list of products
I am trying to build a backbone.js app with Ruby on Rails on the server side.
I am able to get the list of products and that looks great.
Next task is to display the product details when a user clicks on the product. As per my code when I click on a product I then get an alert message "/products/20.json".
Question: Do I need to manually make an ajax call using jQuery or should backbone.js help me get the value for this product given that Backbone.js is REST compliant?
$(function(){
window.Product = Backbone.Model.extend({
defaults: { name: 'name missing' },
urlRoot: '/product'
});
window.ProductList = Backbone.Collection.extend({
model: Product,
url: '/products.json'
});
win开发者_如何学Pythondow.ProductViewForListing = Backbone.View.extend({
initialize: function() {
this.template = $('#productTmplForListing').template(),
_.bindAll(this, 'render');
},
className: 'product',
render: function(){
var fragment = $.tmpl(this.template, this.model.toJSON());
$(this.el).html(fragment);
return this;
}
});
window.ProductViewForShow = Backbone.View.extend({
el: $('#main'),
initialize: function(){
_.bindAll(this, 'render');
this.render();
},
render: function(){
self.el.append($('Hello world'));
}
});
window.AppView = Backbone.View.extend({
el: $('#products'),
events: {
"click .product": "showProduct"
},
initialize: function(){
_.bindAll(this, 'render');
this.render();
},
render: function(){
var self = this;
this.collection.each(function(product){
var view = new ProductViewForListing({model: product});
self.el.append(view.render().el);
});
},
showProduct: function(e){
console.log(e);
var href = $(e.target).closest('.product').find('a').attr('href');
alert(href);
}
});
var products = new ProductList();
products.fetch({
success: function() {
new AppView({ collection: products });
}
});
});
<script type="text/x-jquery-tmpl" id="productTmplForListing">
<a href="/products/${id}.json">
<img alt="${name}" class="productImage" height="190" src="/system/pictures/${id}/thumbnail/${picture_file_name}" width="190" />
</a>
<p class="productName">
<a href="/products/${id}.json">
${name}
</a>
</p>
<p class="productPrice">
${price}
</p>
</script>
Your products
Collection, after calling fetch
, should have an array of fully formed Product Models, assuming that your rails products controllers index action looks something like:
def index
products = Product.all
render :json => products
end
In other words, the Product model that you pass to your ProductViewListing
is already fully in memory. It just so happens that you're only accessing the id
attribute in your template.
In short the answer to your question is no, you don't need to manually make an ajax call, because you already have all of the models' info in your Products collection.
精彩评论