Backbone: Parsing data and overriding toJSON

Using parse on Collection or Model to massage data then using toJSON to set it all back to normal when getting ready to send to server.

by kyllle

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<div class="js-ctn"></div>

<script type="text/html" class="js-template">
    <h1>Hey, <%= fullName %></h1>
</script>

CSS

@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,500);

body {
    font-family: Roboto;
    color: #191919;
}

a {
    color: #191919;
}

JavaScript

console.clear();

// Dummy Data
var data = {
    "person": { //we want to remove this person wrapper
        "id": 1,
        "name": "John Doe" //we want to make this `fullName`
    }
}

// Classes
var Model = Backbone.Model.extend({
    
    parse: function(response) {
        console.info('response::start', response);
        
        // Make the reponse start at `person`
        response = response.person;
        
        // Also want to swap `name` to be `fullName`
        response.fullName = response.name;
        
        // Now remove the unrequired `name` entry
        delete response.name;
        
        console.info('response::end', response);
        
        return response;
    },
    
    // POSTing back to server the Model needs to be
    // reset to the original response settings so we 
    // override the toJSON method
    toJSON: function() {
        
        // Original Backbone toJSON returns a cloned copy of the model attributes - but we want to fix up out data first
        var attributes = _.clone(this.model.attributes);
        
        // Reset the new `fullName` property back to `name`
        attributes.name = attributes.fullName;
        
        // Now remove the `fullName` property as unrequired
        delete attributes.fullName;
        
        // Now go ahead adnd return the attributes but make sure to wrap it in object tags and assign the key `person` like our original
        return {"person": attributes};
        
        // NOTE: Because we are overriding the Models toJSON method we will no longer be able to use this.model.toJSON() in our views, instead use this.model.attributes.
    }
});
var View = Backbone.View.extend({
    
	template: _.template( $('.js-template').html() ),
     
    render: function() {
		this.$el.html( this.template( this.model.attributes ) ); //or this.model.attributes if toJSON() overrid
        
        return this;
    }
});

// Setup
var newModel = new Model(data, {parse:true});
var newView =...