我正在尝试为通过链接访问的帖子设置显示页面:
<a class="post-link button" href="#">details</a>
当 post item 被渲染时,它会被赋予一个 href,如下所示:
this.$('a').attr('href', this.postUrl());
...
postUrl: function() {
return "#posts/" + this.model.get('id');
}
呈现字段时,链接显示为:
http://[path_to_app]/#posts/[whatever_id]
当我点击链接时,它应该会点击这个路由器:
routes: {
'' : 'index',
'new' : 'newPost',
"posts/:id" : 'show'
}
但是我收到了这个错误,它根本不会进入 show 函数:
Uncaught Error: Syntax error, unrecognized expression: /1 jquery.js:4268
Sizzle.errorjquery.js:4268
Sizzle.filterjquery.js:4254
Sizzlejquery.js:4044
Sizzlejquery.js:5176
jQuery.fn.extend.findjquery.js:5432
jQuery.fn.jQuery.initjquery.js:188
jQueryjquery.js:28
hashchangetabs.js:9
jQuery.event.dispatchjquery.js:3333
jQuery.event.add.elemData.handle.eventHandle
当我将链接更改为“#post/”+ id 并将路由更改为“post/:id”时,不会发生此错误。
我正在学习Backbone,在这里真的可以用一只手。另外值得注意的是:我的路由根到 posts#index 操作。
编辑(更相关的代码):
# Model
[APP].Models.Post = Backbone.Model.extend({
urlRoot: '/posts'
});
#Router
[APP].Routers.Posts = Support.SwappingRouter.extend({
initialize: function(options) {
this.el = $('#posts');
this.collection = options.collection;
},
routes: {
'' : 'index',
'new' : 'newPost',
"posts/:id" : 'show'
},
index: function() {
var view = new [APP].Views.PostsIndex({ collection: this.collection });
this.swap(view);
},
newPost: function() {
var view = new [APP].Views.PostsNew({ collection: this.collection });
this.swap(view);
},
show: function(postId) {
var post = this.collection.get(postId);
var postsRouter = this;
post.fetch({
success: function() {
var view = new [APP].Views.PostShow({ model: post });
postsRouter.swap(view);
}
});
}
});
#Post Item View
[APP].Views.PostItem = Backbone.View.extend({
tagName: 'tr',
initialize: function() {
_.bindAll(this, 'render');
},
render: function () {
this.$el.attr('id', 'post_' + this.model.id);
this.$el.html(JST['posts/item']({ post: this.model }));
this.renderFormContents();
return this;
},
renderFormContents: function() {
...
this.$('a').attr('href', this.postUrl());
},
postUrl: function() {
return "#posts/" + this.model.get('id');
}
});