简体   繁体   中英

Accessing javascript object attributes in Backbone.js

Tastypie provides a RESTful API for django projects so I can use Backbone.js. When I hit the url to get a collection of resources, tastypie includes data about pagination, which I am unable to access. I have a Backbone View where I initialize a collection in the initialize function, then render:

MyView = Backbone.View.extend({
  ...
  initialize: function() {
     this.collection = new MyCollection;
     this.render();
  }
  ...
  render: function() {
     console.log(this.collection); // this.colllection.toJSON() returns []
     console.log(this.model);  // this.model.toJSON() returns the object
  }
});

The link for the next page is contained in the meta attribute of this.collection, but I cannot access it. Calling toJSON() on the collection returns []. The issue is that the console.log(this.collection) gives this:

> child
_byCid: Object
_byId: Object
_callbacks: Object
length: 3
meta: Object
models: Array[3]
toJSON: function (key) {
__proto__: ctor

The url I want is inside the meta attribute of this.collection (so I can see it!), but I can't access it. Calling toJSON works on the model, but not the collection. How I can access the attributes of the collection?

Can be as simple as this.collection.meta ?

Update

Also you have to use console.log carefully and don't trust on it when you are debugging not simple objects, check:

In your code try:

this.collection.fetch({
  success: function( collection ) { 
    console.log( "collection.meta", collection.meta ) 
  } 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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