Backbone.js - it is impossible to get data or bind to a selection event in the collection?

I am using jQuery 1.7.1, Underscore 1.3.1 and Backbone 0.9.1. This is my basic code, in full:

$(function(){ window.Student = Backbone.Model.extend({ }); window.Students = Backbone.Collection.extend({ model: Student, }); window.AllStudents = new Students(); AllStudents.url = "/init.json"; AllStudents.bind('reset', function() { console.log('hello world'); }); AllStudents.fetch(); AllStudents.fetch({ url: "/init.json", success: function() { console.log(AllStudents); }, failure: function() { console.log('failure'); }}); AllStudents.fetch({ url: "/init.json" }).complete(function() { console.log(AllStudents); }); }); 

In the third call to .fetch() , only one console statement appears, and then it is an empty object.

I am puzzled. What am I doing wrong? How can I bind to the reset event and work with the extracted data?

This is the JSON file:

 [ { text: "Amy", freq_2011: 5 }, { text: "Angeline", freq_2011: 26 }, { text: "Anna", freq_2011: 55 } ] 

I checked that the JSON file is being processed as application / json, and I also see that it receives an XHR request three times.

UPDATE: This is my HTML, in full:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Test</title> </head> <body> <div class="container"></div> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.1/underscore-min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.1/backbone-min.js"></script> <script src="/js/test.js"></script> </body> </html> 

Can others reproduce the problem?

+4
source share
1 answer

The trunk has a nice function that can be overridden by parse , which receives the extracted data as its arguments after calling a successful fetch. You can use this to process your JSON after loading it, for example:

 window.Students = Backbone.Collection.extend({ model: Student, parse: function(response) { console.log(response,response.results); return response.results; } }); 
0
source

Source: https://habr.com/ru/post/1398276/


All Articles