0
我建立使用Rails 3. Backbone.js的應用程序當我展示的產品名單,並在頂部點擊一個產品,我看到的網址一樣hashbang沒有正確刷新頁面時硬refersh
http://localhost:3010/#products/20
但是,當我硬刷新網頁,我沒有看到產品信息。在服務器端,而不是爲產品提供了JSON請求我看到以下
Started GET "/" for 127.0.0.1 at 2011-08-11 13:26:38 -0400
Processing by HomeController#index as HTML
這裏是我的JavaScript代碼
$(function(){
window.Product = Backbone.Model.extend({
defaults: { name: 'name missing' },
urlRoot: '/products'
});
window.ProductsList = Backbone.Collection.extend({
model: Product,
url: '/products'
});
window.ProductViewForListing = Backbone.View.extend({
template: $('#productTmplForListing').template(),
initialize: function() {
_.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({
template: $('#productTmplForShow').template(),
initialize: function(){
_.bindAll(this, 'render');
this.render();
},
render: function(){
var fragment = $.tmpl(this.template, this.model.toJSON());
$(this.el).html(fragment);
return this;
}
});
window.AppView = Backbone.View.extend({
el: $('#products'),
initialize: function(){
_.bindAll(this, 'render', 'showProduct');
this.render();
},
render: function(){
var targetElement = $('#products');
var self = this;
this.collection.each(function(product){
var view = new ProductViewForListing({model: product}),
fragment = view.render().el;
self.el.append(fragment);
});
},
showProduct: function(id){
var product = new Product({id: id}), self = this;
product.fetch({
success: function(){
var mainElement = self.el.closest('#main'),
view = new ProductViewForShow({model: product});
mainElement.find('#products').html('');
self.el.append(view.render().el);
},
error: function(){ alert('error getting product details'); }
});
return false;
}
});
window.products = new ProductsList();
window.AppRouter = Backbone.Router.extend({
initialize: function(){
},
routes: {
'': 'home',
'products/:id': 'showProduct'
},
home: function(){
var self = this;
window.products.fetch({
success: function(){
self.appView = new AppView({ collection: window.products });
self.appView.render();
}
});
},
showProduct: function(id){
window.App.appView.showProduct(id);
}
});
window.App = new window.AppRouter();
Backbone.history.start({pushState: false});
});
這裏是我的索引模版
<script type="text/x-jquery-tmpl" id="productTmplForListing">
<a href="#products/${id}" data-id='${id}'>
<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}">
${name}
</a>
</p>
<p class="productPrice">
${price}
</p>
</script>