backbonejs - 在视图中访问 collection

backbonejs - accessing collection in view

这里是 backbonejs 和 oop js 新手。我试图将我的 collection 绑定到一个视图,当我转到我的控制台时,我只得到这个 这是一个 collection: [object Object]

我在这里遗漏了什么吗?

  var root = "http://jsonplaceholder.typicode.com";

  var Post = Backbone.Model.extend({});

  var Posts = Backbone.Collection.extend({
    model: Post,
    url: root + "/posts",
    parse: function(response) {
      return response;
    }
  });
  var posts = new Posts();
  posts.fetch();

  // View wrapper to render view child items
  var PostsView = Backbone.View.extend({
    collection: new Posts(),
    initialize: function() {
      console.log('this is a collection: ' + this.collection);
    },
    render: function() {
      // STEPS:
      // filter through all items in a collection
      // for each item, create a new PostView
      // append to root element, ex. ul
    }
  });
  var postsview = new PostsView();

当您执行 'this is a collection: ' + this.collection 时,您强制集合成为一个字符串,并且 javascript 看到一个对象并将其转换为您的 [object Object].

将集合显示为字符串的正确方法是仅使用其 .toJSON() 函数并执行 console.log('this is a collection: ' + JSON.stringify(this.collection.toJSON())); 但由于大多数开发工具都能够在本地正确显示对象,因此您最好使用

console.log('this is a collection: ', this.collection);

至少在 Chrome。