我有一个简单的路由器:
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);
}
});
is的模板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>
GalleryView 和 GalleryItem 代码。
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
并在有人访问该页面时进行该工作。我错过了什么吗?实现了一些奇怪的东西?朝正确方向轻推将不胜感激。
谢谢。