我的应用程序中有一个主主页,每个帖子都有另一个页面,可以通过主页中显示的列表进行访问。
这是我的路由器的样子:
var AppRouter = Backbone.Router.extend({
initialize: function(){
this.model = new model();
this.collection = new collection();
},
routes: {
"" : "showForm",
"post/:id" : "showPost"
},
showPost: function(id){
var curmodel = this.collection.get(id);
var post = new postView({model:curmodel});
post.render();
$(".maincontainer").html(post.el);
},
showForm : function(){
var qcView = new qcV({model:this.model, collection:this.collection});
qcView.render()
$(".maincontainer").html(qcView.el);
}
});
这是此列表中帖子的链接之一
<h2><a id= "<%=_id%>" href="#post/<%=_id%>"><%=name%></h2></a>
我的第一个问题是:以这种方式使用基于散列的 URL 链接页面是否危险?
我的第二个问题是:如果我单击主页中的其中一个链接,我可以毫无问题地导航到帖 subview 。我的 url 成功更改为类似 http://127.0.0.1:3000/#post/51ffdb93c29eb6cc17000034
并且呈现特定帖子的 View 。但是,此时如果我刷新页面,或者如果我直接键入 http://127.0.0.1:3000/#post/51ffdb93c29eb6cc17000034
到我的 URL 栏,this.collection.get( id)
方法在我的路由器中的 showPost 方法中返回 undefined
。谁能帮我弄清楚为什么会这样?
我检查了几次我的初始化方法被调用了两次,并且我的集合和模型创建成功
最佳答案
对于 #2,您很可能不会在“post”路径上获取集合。尝试获取集合(如果它不存在)然后调用 render。这应该可以解决问题!
关于javascript - Backbone 集合 get(id) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18064076/