Eran Medan
Eran Medan

Reputation: 45755

Saving model on each change, except the first initial fetch

I'm sure it's a very common and basic Backbone question, but I couldn't find the answer

I would like to save a model after each change, except the initial fetch from the server.

For example:

  MyModel = Backbone.Model.extend({
    url: "myModelUrl",
    initialize: function () {
      this.on("change", this.save, this);
    }
  });

When fetching it, since it has some data, I get a change event, and then save is triggered again

 var myModel = new MyModel({id:"123"}); 
 myModel.fetch(); 

Is there a way to avoid the first save on the first fetch? (e.g. if the model was just fetched, don't save)

Could it be that the only way is to bootsrtap the models?

e.g. based on the documentation, is this really the only way to do it?

Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place. fetch is intended for lazily-loading models for interfaces that are not needed immediately: for example, documents with collections of notes that may be toggled open and closed.

Edit:

One issue I see with bootstrapping is this - it seems I have to fetch my entire collection on page load, I can't fetch only small parts of it. Why? because if my routes use a hash tag, on page refresh, the server side won't know which route I'm in (hash part is not sent to the server). e.g. only if I use pushState: true I can get to be able to bootsrap the right model / collection on page refresh, am I missing something?

Upvotes: 0

Views: 411

Answers (2)

Venkat Kotra
Venkat Kotra

Reputation: 10753

sync is the event that is fired when a model is fetched. Listen to the sync even only once. Later to that listen to change event on the model.

var self;     
this.listenToOnce(model,'sync', function(){
   self.listenTo(model,'change',self.changeHandler);
});

Upvotes: 3

yujingz
yujingz

Reputation: 2389

Don't quite understand your requirements. But if you just want to avoid the first save, you could manually set an attribute

isFirstSave = true

and make your binding methods like this

onModelChange: =>
  if @isFirstSave
    @isFirstSave = false
  else
    @save()

Ugly but works..

Upvotes: 0

Related Questions