JSFiddle - React, Tailwind, and code Playground

by Leigh Quince

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.13/backbone.localStorage-min.js"></script>

JavaScript

var app = app || {};

Backbone.Model.prototype.toJSON = function () {
    var json = _.clone(this.attributes);
    for (var attr in json) {
        if ((json[attr] instanceof Backbone.Model) || (json[attr] instanceof Backbone.Collection)) {
            json[attr] = json[attr].toJSON();
        }
    }
    return json;
};
// List Collection - list of words
//---------------------


app.WordModel = Backbone.Model.extend({});
app.ListModel = Backbone.Model.extend({

    initialize: function () {
        // because initialize is called after parse
        _.defaults(this.attributes, {
            words: new app.WordCollection()
        });
    },
    parse: function (response) {
        if (_.has(response, "words")) {
            this.attributes.words = new app.WordCollection(response.words, {
                parse: true
            });
            delete response.words;
        }
        return response;
    }
});

app.ListCollection = Backbone.Collection.extend({
    //referebce to this collection's model
    model: app.ListModel,
    localStorage: new Backbone.LocalStorage('translate-lists')
});
app.WordCollection = Backbone.Collection.extend({
    //referebce to this collection's model
    model: app.WordModel,
    localStorage: new Backbone.LocalStorage('words')
});

app.listCollection = new app.ListCollection();
app.listCollection.create({
    text: "some thing",
    words: [{
        value: "a"
    }, {
        value: "b"
    }, {
        value: "c"
    }, {
        value: "d"
    }]
}, {
    parse: true // tell the collection to parse the data
});


app.listCollection.fetch();
console.log(app.listCollection.toJSON());
console.log(app.listCollection);