ruby on rails - Unable to iterate over collection in Backbone template -


i'm new coding in general , picking backbone rails. attempt iterate collection data within template has failed , i'm not sure what's wrong. when loading webpage seems json data , part of template loads fine bit iteration fails. here's code:

acquisition.js:

var acquisition = backbone.model.extend({ }); 

acquisitions.js:

var acquisitions = backbone.collection.extend({   model: acquisition,   url: '/acquisitions.json' }); 

acquisitions_index.js:

var acquisitionsindex = backbone.view.extend({     tagname: "table",     render: function() {       this.$el.html(jst['acquisitions/index']({ collection: this.collection }));       return this;     } }); 

index.jst.ejs:

<tbody>   <tr>     <th>cash(usd)</th>     <th>date</th>   </tr>   <% collection.each(function(model) { %>   <tr>     <td><%= model.escape('cashusd') %></td>     <td><%= model.escape('date') %></td>   </tr>   <% }); %> </tbody> 

home.html.erb:

<header>   <h1>startup acquisitions</h1> </header>   <div id="app"></div> <script>   var acquisitions = new acquisitions;   acquisitions.fetch();    var acquisitionsindex = new acquisitionsindex({collection: acquisitions});   acquisitionsindex.render();   $("#app").append(acquisitionsindex.el) </script> 

to put mu short's correct advice answer, important understand tha "a" in ajax stands asynchronous, means when fetch, client side javascript keeps on executing. not block , wait fetch returned. while code reads like:

  1. fetch collection
  2. receive collection items response
  3. create view
  4. render collection in view :)

you experiencing:

  1. fetch collection
  2. create view
  3. render empty collection in view :(
  4. receive collection items response (what happened there?).

so mu short comments, events come play. example amend code block be:

var acquisitions = new acquisitions; var acquisitionsindex = new acquisitionsindex({collection: acquisitions}); acquisitionsindex.listento(acquisitions, "sync", acquisitionsindex.render); acquisitions.fetch(); 

this code means view listening "sync" event on collection, signifies when collection synced server. when sync event occurs, render function on view called last argument in listento function. ensure view inserted document, might change render function to:

render: function() {     this.$el.html(jst['acquisitions/index']({ collection: this.collection }));     $("#app").append(this.$el);     return this; } 

keep in mind if chaining view render calls, better document insertion $("#app").append(this.$el); after have done chaining (to prevent multiple document reflows, put line in render function simplicity in example.


Comments