Why Backbone.Model#toJSON is called on Backbone.Model#fetch? #77

Closed
michael opened this Issue Nov 15, 2010 · 2 comments

Projects

None yet

2 participants

@michael

I just realized that Backbone.Model#toJSON gets called on every Backbone.Model#fetch. It even gets called when when a corresponding Collection is fetched. Is this intensional? I'd expect toJSON to be called only on Backbone.Model#save. I'm using Backbone 0.0.3.

This causes problems in my case since my models (documents) aren't in a valid (serializable state) before they've been fetched and parsed.

In my scenario I'd like to load a document by just creating a new Document with an id property, then calling fetch.

loadDocument: function(id) {
  this.model = new Document({id: id});
  this.model.fetch({
    success: function() {
      // init doc
    }
  });
},

toJSON is unnecessarily (imo) called here, causing an error, because the document's ContentGraph (this.g) hasn't been setup properly.

toJSON: function() {  
  return _.extend(_.clone(this.attributes), {
    contents: this.g.serialize()
  });
},

My parse function looks like this:

parse: function(res) {
  if (res.contents) {
    this.g = new ContentGraph(res.contents);
  }
  return res;
},
@michael

Argh. The body of this issue just disappeared, when I updated the issue's title. Now typing the whole thing again...

@jashkenas
Owner

Thanks for taking the time to retype it. I've fixed the bug here:

86c3089

And pushed it out as Backbone 0.3.1. Closing the ticket...

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment