简体   繁体   English

骨架js-访问视图中的集合

[英]backbonejs - accessing collection in view

backbonejs and oop js newbie here. 此处有ribsjs和oop js新手。 i am trying to bind my collection to a view, when i go to my console, i only get this this is a collection: [object Object] 我试图将我的收藏集绑定到视图,当我进入控制台时,我只会得到以下内容:[object Object]

is there something am i missing here? 我在这里缺少什么吗?

  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();

When you do 'this is a collection: ' + this.collection you're forcing the collection to be a string, and javascript sees an object and turns it into your [object Object] . 当您执行'this is a collection: ' + this.collection您将集合强制为字符串,而javascript会看到一个对象并将其变成[object Object]

The correct way to show a collection as a string is to just its .toJSON() function and do console.log('this is a collection: ' + JSON.stringify(this.collection.toJSON())); 将集合显示为字符串的正确方法是仅使用其.toJSON()函数并执行console.log('this is a collection: ' + JSON.stringify(this.collection.toJSON())); but since most devtools are capable of properly showing an object natively you're better off using 但是由于大多数devtools都可以正常显示本机对象,因此最好使用

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

That should give you a nice interactive representation of the collection in your console, at least on Chrome. 至少在Chrome上,这应该可以让您在控制台中很好地交互表示集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM