我想要完成的是将这个帖子模型 ID 传递给一个集合,以便我可以用与其关联的其他模型填充这个特定的帖子 ID。例如:在博客文章中,包含一堆评论。我只想显示那些指向此博客文章的评论。
我一定错过了一些基本的东西。
下面是我的帖子模型,我正在实例化一个新的 CommentCollection 并传递模型和选项参数。
var PostModel = Backbone.Model.extend({
initialize: function() {
/*
* we are connecting Comments collection
* to each post item by passing along post id
* */
this.comments = new CommentsCollection([], { id: this.id });
},
defaults: {
title: 'title here',
body: 'body here'
},
urlRoot: localserver + "/posts"
});
以下是我的评论集。 console.log(this.id);
返回未定义。
var CommentsCollection = Backbone.Collection.extend({
initialize: function(models, options) {
this.id = options.id;
console.log(this.id);
return this;
},
url: function() {
console.log(this.id);
return localserver + "/posts/" + this.id + "/comments";
},
model: CommentModel
});
我的控制台返回以下内容:
Uncaught TypeError: Cannot read property 'id' of undefined
3
最佳答案
试试这个代码:
var CommentModel = Backbone.Model.extend({});
var CommentsCollection = Backbone.Collection.extend({
model: CommentModel,
initialize: function(models, options) {
this.id = options.id;
if(typeof this.id === 'undefined') { return; }
this.url();
},
url: function() {
var localserver = "localhost";
console.log('from comment url: ', this.id);
return localserver + "/" + this.id + "/comments";
}
});
var PostModel = Backbone.Model.extend({
urlRoot: "http://jsonplaceholder.typicode.com" + "/posts",
initialize: function(option) {
this.comments = new CommentsCollection([], { id: option.id });
}
});
//var pm = new PostModel();
//pm.comments.fetch();
//console.log('from pm: ', pm.comments.url());
var PostsCollection = Backbone.Collection.extend({
model: PostModel,
url: "http://jsonplaceholder.typicode.com" + "/posts?_sort=views&_order=DESC",
initialize: function() {
this.on('reset', this.getComments, this);
},
getComments: function() {
this.each(function(post) {
post.comments = new CommentsCollection([], { post: post });
post.comments.fetch();
});
}
});
var pc = new PostsCollection();
pc.fetch();
我所做的是使用PostModal的选项参数。下面是代码。
var PostModel = Backbone.Model.extend({
urlRoot: "http://jsonplaceholder.typicode.com" + "/posts",
initialize: function(option) {
this.comments = new CommentsCollection([], { id: option.id });
}
});
关于javascript - Backbonejs - 在集合中,我们如何从初始化函数访问 this.var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32168065/