我有一个简单的路由器:
Erin.Router = Backbone.Router.extend({
initialize: function() {
Backbone.history.start({pushState: true});
},
routes: {
'' : 'index',
'project/:img' :'project',
},
index: function() {
var galleryView = new Erin.GalleryView();
},
project: function(img) {
console.log(img);
}
});
< p > Erin.GalleryView
的模板可能存在问题:
<script type="text/template" id="gallery-grid">
<a href="/project/<%= id %>">
<img src="<%= thumbnail %>" />
<span class="desc">
<div class="desc-wrap">
<p class="title"><%= title %></p>
<p class="client"><%= client %></p>
</div>
</span>
</a>
</script>
画廊视图和画廊项代码。
Erin.GalleryItem = Backbone.View.extend({
tagName: 'div',
className: 'project-container',
//Grab the template html
template: _.template($('#gallery-grid').html()),
//Set up the render function
render: function() {
//What is the $el in this case?
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
Erin.GalleryView = Backbone.View.extend({
el: '#projects',
initialize: function() {
//create new collection
this.col = new Erin.Gallery();
//Listen to all events on collection
//Call Render on it
this.listenTo(this.col,'all',this.render);
//Fetch data
this.col.fetch();
},
render: function() {
//Get reference to the view object
var that = this;
//Empty div
this.$el.empty();
//For each model in the collection
_.each(this.col.models, function(model){
//call the renderItem method
that.renderItem(model);
},this);
},
renderItem: function(model) {
//create a new single item view
var itemView = new Erin.GalleryItem({
model:model
});
//Append items to to element, in this case "#projects"
this.$el.append(itemView.render().el);
}
});
然后我有一个准备好的文档。
$(function() {
var router = new Erin.Router();
$('#projects').on('click', 'a[href ^="/"]', function(e){
e.preventDefault();
router.navigate($(this).attr('href'),{trigger: true});
});
});
当您加载页面并单击“#project”部分中的某个链接时,一切都表现正常。但是如果您刷新该页面,则会出现破坏页面的错误。
从控制台中可以看到:
Uncaught SyntaxError: Unexpected token < js/jquery.js:1
Uncaught SyntaxError: Unexpected token < js/underscore-min.js:1
Uncaught SyntaxError: Unexpected token < js/backbone.js:1
Uncaught SyntaxError: Unexpected token < erin.js:1
它还列出了以下内容:
...
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/project/js/backbone.js".
针对文档头部的所有链接和脚本。这些似乎都指向index.html文件的第一行。所以,如果我点击一个链接,它会从我的数据中输出我正在查找的img id,但如果我刷新页面或输入该链接,则会出现上面的错误。我是否正确地认为当有人访问该页面时,我应该能够保存链接domain.com/project/coolthing
并使其正常工作?我错过了什么吗?是否实现了一些奇怪的东西?非常感谢给出正确方向的提示。
谢谢。