BB: Collection Save

by mdoye

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-person-tmpl">
    <h1>Hey, <%= name %></h1>
    <p><%= playerPoints %></p>
        
    <ul>
        <% _.each(teams, function(team) { %>
            <li><%= team.name %> (<%= team.location %>) - <small><%= team.manager %></small></li>
        <% }) %>
    </ul>
</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();
Backbone.emulateHTTP = true;
Backbone.emulateJSON = true;

// Classes
var PersonModel = Backbone.Model.extend({});

var PersonCollection = Backbone.Collection.extend({
    url: '/echo/json/',
    model: PersonModel,
    toJSON: function() {
        return this.models.map(function(model) {
            return _.pick( JSON.stringify(model.toJSON()), "id","name", "teams" )
        });
    },
	save: function() {
        Backbone.sync('create', this, {
            success: function(data, textStatus, jqXHR) {
                console.log('Saved!', data);
            }
        });
    },
});

var PersonCollectionView = Backbone.View.extend({
    events: {
        'click .js-post-data': 'onDataSubmit'
    },
    tagName: 'ul',
    render: function() {
		this.collection.each(this.addPerson, this);
        this.$el.append('<button class="js-post-data">Post Data</button>');
        return this;
    },
    addPerson: function(person) {              
        var personView = new PersonView({
            model: person
        });	
        this.$el.prepend( personView.render().el )
    },
    onDataSubmit: function(event) {
        event.preventDefault();
		this.collection.save();
    }
});

var PersonView = Backbone.View.extend({
    tagName: 'li',
    template: _.template( $('.js-person-tmpl').html() ),
    render: function() {
        this.$el.html( this.template( this.model.toJSON() ) );
        return this;
    }
});

// Setup
function init () {
    var personCollection = new PersonCollection(data, {parse:true});
    var personCollectionView = new PersonCollectionView({
        collection: personCollection
    });
    // Add to DOM
    $('.js-ctn').html(personCollectionView.render().el);
}
// Dummy Data
var data = [
    {
        "id": 1,
        "name": "John Doe",
        "sessions": ["A1234", "E3456"],
        "teams": {
            "PL678": {
                "id": 12,
                "name": "Manchester United",
                "manager": "Louis van...