0

I am making a service call using collection url. The service returns some json, the json length is 13 (in short 13 rows of data).

Here, this.Collection.fetch() is returning json who's length is 13. but this.Collection.toJSON() is returning json who's length is 12. instead it should return length 13.

In collection parse, the response is returning json who's length is 13, which is correct!

tableTemplate is object of template (template is done using Handlebars.js).

this.Collection.fetch({ success: function(){

        console.log("Collection Fetch 2:");
        console.log(this.Collection.fetch());

        console.log("Collection toJSON: ");
        console.log(this.Collection.toJSON());
        console.log(this.Collection.toJSON().length);


        var markup = tableTemplate({List:self.importCollection.toJSON()});
         ...
          ...
    }
});
Ashwin Hegde
  • 857
  • 2
  • 8
  • 11
  • some more context would help – JamesHalsall Feb 13 '13 at 12:31
  • 1
    It's unclear what you'd be expecting to work when calling `fetch` inside of the callback for `fetch` for the same collection. The second `fetch` also would be async. – WiredPrairie Feb 13 '13 at 12:57
  • Can you please review it again and explain me whats going on in my code. – Ashwin Hegde Feb 13 '13 at 13:17
  • can you show the output of console.log here. – coderek Feb 13 '13 at 13:33
  • Are there columns with the same name? From what you've observed, what column is being removed when `toJSON()` is called? – Dennis Rongo Feb 13 '13 at 13:41
  • Actually, 1 complete rows is not displayed. I think there are 2 rows with same id, Is this be an Issues But i have not used any rendering logic in template. what data is coming from JSON, It will be directly passed to handlebars template and the rows are displayed. – Ashwin Hegde Feb 14 '13 at 05:40

1 Answers1

1

Thats the asynchronous nature of javascript/backbone

do it like this :

this.collection.fetch();

//Fetch() is asynchronous call , when it completes fetching it triggers the **reset**   event so you need a event listener for **reset**

this.collection.on('reset',function(data){
console.log(data);                          // this will log the object
});

this.collection.on('reset',function(data){
console.log(JSON.stringify(data));        // This will log the JSON data  
});

OR you could do this :

this.collection.fetch({
success : function(){                      // called on completion of fetch()
console.log(data);       
console.log(JSON.stringify(data));  
}
});
Nishant Jani
  • 1,965
  • 8
  • 30
  • 41