问题在于app.js文件中的PostRouter变量。记录this.posts.toJSON()会返回我的数据库中的数据,但调用get传递id将返回undefined。路由在id在URL中传递并记录在我的函数中时起作用。我使用Mongo存储数据和Monk来查询数据库。
我的服务器文件
//configure
app.configure(function(){
app.use(express.json()); //parses the JSON requests being sent to the server
app.use(express.static( path.join(__dirname, 'public') )); //serve files from the path given
});
app.get("/posts", function(req, res){
var db = req.db;
db.get("postscollection").find({}, function (err, results) {
res.json(results);
});
});
//create route using Express REST API
app.get('/*', function(req, res){
var db = req.db;
db.get("postscollection").find({}, function (err, results) {
res.render("index.ejs", { posts: JSON.stringify(results) }); //pass object of values to use in template
});
});
app.listen(3000);
我的应用文件
//Post
var Post = Backbone.Model.extend({});
//Posts
var Posts = Backbone.Collection.extend({
model: Post,
url: "/posts"
});
//PostListView
var PostListView = Backbone.View.extend({
tagName: 'li',
template: _.template("<a href='/posts/{{_id}}'>{{title}}</a>"),
render: function () {
this.el.innerHTML = this.template(this.model.toJSON()); //this.model is view instance
return this;
},
events: {
'click a': 'handleClick'
},
handleClick: function (e) {
e.preventDefault();
postRouter.navigate($(e.currentTarget).attr("href"), { trigger: true }); //navigate to specified route and trigger routing
}
});
//PostsListView
var PostsListView = Backbone.View.extend({
template: _.template("<h1>My Blog</h1><ul></ul>"),
render: function () {
this.el.innerHTML = this.template();
var ul = this.$el.find("ul"); //this.$el == $(el)
this.collection.forEach(function (post) {
ul.append(new PostListView({ model: post }).render().el);
});
return this;
}
});
//PostView
var PostView = Backbone.View.extend({
events: {
'click a': 'handleClick'
},
initialize: function(){
_.bindAll(this, "render");
this.template = _.template($("#postView").html()); //to prevent template from loading before scripts
},
render: function () {
var model = this.model.toJSON();
this.el.innerHTML = this.template(model);
return this;
},
handleClick: function (e) {
e.preventDefault();
postRouter.navigate($(e.currentTarget).attr("href"), {trigger: true});
}
});
//PostRouter
var PostRouter = Backbone.Router.extend({
initialize: function (options) {
this.posts = options.posts; //the posts collection
this.main = options.main; //the main id div in the view
},
routes: {
'' : 'index',
'posts/:id': 'singlePost'
},
index: function () {
var pv = new PostsListView({ collection: this.posts });
this.main.html(pv.render().el);
},
singlePost: function (id) {
console.log("view post " + id); //logs id passed
console.log(this.posts.toJSON()); //logs data in db
var post = this.posts.get(id); //returns undefined
var pv = new PostView({ model: post });
this.main.html(pv.render().el);
}
});
索引工作正常并显示我的所有数据,但尝试查看单个帖子会破坏应用程序。