Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bootstrap a collection in Backbone.js using Javascript only

Context: I am building an application that needs several large collections of reference data to operation. I am limited to HTML and Javascript only (including JSON).

Question: How do I bootstrap a collection in Backbone.js where the collection objects are in JSON format on the server and I'm using Javascript only?

This is what I know already:

  • Backbone.js bootstrapping best practice requires Rails or some other server-side language (http://backbonejs.org/#FAQ-bootstrap).
  • Most Javascript I/0 operations are asynchronous, such as loading JSON from the server.
  • Using fetch() to bootstrap data is considered an anti-pattern in Backbone.js. fetch() is also also an asynchronous operation.

This is what I've come up with so far:

ItemList = Backbone.Collection.extend({
  model: Item,
  url: 'http://localhost:8080/json/items.json'
});
var itemList = new ItemList;
itemList.fetch();
itemList.on('reset', function () { dqApp.trigger('itemList:reset'); });

'dqApp' is my application object. I can display a spinner, and update a loading status while collections are being populated by sending alerts to the application object.

like image 460
Mr The Falcon Avatar asked Jun 14 '12 16:06

Mr The Falcon


2 Answers

this may be help you : http://ricostacruz.com/backbone-patterns/#bootstrapping_data

like image 69
Justin wong Avatar answered Oct 03 '22 02:10

Justin wong


The fetch function accepts an options parameter, which can have a success callback:

var itemList = new ItemList;
itemList.fetch({success: function () {
    dqApp.trigger('itemList:reset');
}});
like image 41
Snowball Avatar answered Oct 03 '22 02:10

Snowball