ams
ams

Reputation: 62632

Who is supposed fetch a model in a backbone application?

In a backbone application what is the best practice regarding when a model is fetched? I can see the following possibilities.

Upvotes: 1

Views: 265

Answers (2)

Daniel Aranda
Daniel Aranda

Reputation: 6552

If you want to be standard, your view must render one time when initialize and listen for the change event of the Model and re render the view every time that model changes, that is all. (regarding what does View needs to do when fetch is completed)

And for call the model.fetch() if you follow the standard that I said, no matters where the fetch is called your view will be updated.

Some people could have a module named load in the view where do something like this:

load : function(){
  this.model.fetch();
}

Others could do external fetch call, like this:

var myModel = new YourModel();
var myView = new SomeView( {model : model} );
//Probably you could render with the default data in the while model is fetched
myView.render();
model.fetch();

Upvotes: 1

jakee
jakee

Reputation: 18556

A few best practives:

1 Collections and models that are necessary from the very first milliseconds of the app's life should be 'bootstrapped' in place (so there shouldn't be need to fetch them to gain access to vital data)

So when the user is served the correct pages from the server, the models and collections should be already in place (nice example from backbone.js docs)

 var ExampleCollection = new Backbone.Collection();
 ExampleCollection.reset(<%= @your_collection_data.to_json() %>); // Or whatever your server-side language requires you to do, this is a ruby example

2 The rest can be fetched just in time

The models and collections that aren't needed at the moment your app is initialized can be fetched whenever you feel like it, but I think that the logical time to do that is when the user expresses intent to use those models. E.g. user presses a button to open a view that needs some model/collection -> fetch that collection, user wants to clear unsaved changes from a model -> fetch that model from the server to get the last saved status of the model, and so forth. Usually the place where the fetching is bound to happen is the view that 'owns' the model/collection, because it relays the users actions to the model and displays the model's state to the user.

But like it was said, Backbone.js isn't strict about when a model or collection should be fetched. It can be done anywhere in the app, just make sure you do it only when it's necessary.

Hope this helps!

Upvotes: 1

Related Questions