Backbonejs - 在集合中,我们如何从initialize函数访问this.var?

时间:2015-08-23 14:59:35

标签: javascript backbone.js

我想要完成的是将此Post模型ID传递给集合,以便我可以使用与之关联的其他模型填充此特定Post ID。例如:在博客文章中,包含一堆评论。我想显示那些仅指向此博客文章的评论。

我必须在这里遗漏一些基本的东西。

下面是我的Post Model,我正在实例化一个新的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);返回undefined。

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

1 个答案:

答案 0 :(得分:1)

试试这段代码:

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的option参数。以下是代码。

var PostModel = Backbone.Model.extend({
  urlRoot: "http://jsonplaceholder.typicode.com" + "/posts",
  initialize: function(option) {
    this.comments = new CommentsCollection([], { id: option.id });
  }
});