Mode.parse and Model.toJSON

In notebook:
FrontEndMasters BackboneJS
Created at:
2016-06-09
Updated:
2016-06-09
Tags:
libraries JavaScript
Talks about common response coming back as stringified JSON.

Shows a custom parse function:
  var BookModel = Backbone.Model.extend({
  parse: function(attrs){
    return attrs.book;
  }
})
This will automatically unwrap the data. If it comes in like this:
  {
  "book" : {
    "title": "The Long Goodbye",
    "author": "Raymond Chandler"
  }
}
You can do this:
  book.fetch();
book.get('author');
// = "Raymond Chandler"

Nested resources

Nested data (like MongoDB)
Works with Backbone, but…

No granular change events on the second level of nesting. In this case he would use a ​set​ to add the nested keys to the model:
  {
  "content": "lorem ipsum",
  "author": {
    "email": "hello@example.com",
    "username": "ussss"
    "avatar": "image.jpg"
  }
}
  var CommentModel = Backbone.Model.extend({
  initialise: function () {
    this.author = new UserModel();
  },
  parse: function (attrs){
    if (attrs.author) {
      this.author.set(attrs.author);
    }
    return _.omit(attrs, 'author');
  }
});
So now, the “subdocument” author is also a full Backbone model with events, etc.

Talks about underscores ​.omit​ and ​delete​ in JavaScript. Underscore is more performant than what a normal user could write.

toJSON

The reverse direction
You have to call ​toJSON​ on the sub-model
  var CommentModel = Backbone.Model.extend({
  toJSON: function(options){
    var json = Backbone.Model.prototype.toJSON.call(this);
    if (options && options.author){
      json.author = this.author.toJSON();
    }
  }
  return JSON;
});
to use, pass the ​options.author​ as ​true​:
​comment.toJSON({ author: true });

Talks about how it relates to Backbone’s ​sync​ method.