JSFiddle - React, Tailwind, and code Playground

by philfreo

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script src="https://raw.github.com/PaulUithol/Backbone-relational/master/backbone-relational.js"></script>
Shouldn't see any duplicates below:
<br/>
<div id="results"></div>

JavaScript

// if this was Backbone.Model instead of RelationalModel there's no shown bug
var Random = Backbone.RelationalModel.extend();

var Email = Backbone.RelationalModel.extend();
var Emails = Backbone.Collection.extend({
    model: Email
});

var Contact = Backbone.RelationalModel.extend({
    relations: [{
                type: Backbone.HasMany,
                key: 'emails',
                relatedModel: Email,
                collectionType: Emails,
    }],
    toJSON: function() {
        var data = Backbone.RelationalModel.prototype.toJSON.call(this);
        
        // THIS LINE CAUSES THE PROBLEM (and it shouldn't)
        // Run this fiddle with and without the line below commented.
        data.random = (new Random()).toJSON();
        
        return data;                            
    }
});

var Contacts = Backbone.Collection.extend({
    model: Contact
});

var Foo = Backbone.RelationalModel.extend({
        relations: [
            {
                type: Backbone.HasMany,
                key: 'contacts',
                relatedModel: Contact,
                collectionType: Contacts,
                reverseRelation: {
                    key: 'foo',
                    includeInJSON: 'id'
                }
            }
        ]    
    });

var foo = new Foo({
    contacts: [{
        name: 'John Smith',
        emails: [{email: '[email protected]'}]
    }]        
});

var contacts = foo.get('contacts');

contacts.on('all', function(event) {
    console.log('beginning', event);
    
    // note we are emptying the div so it shouldn't show the same contact twice
    var el = $('#results').empty();
    
    contacts.each(function(contact) {
       var data = contact.toJSON();
       var txt = data.name+' - '+data.emails[0].email+'<br>';
       el.append(txt);
    });
    
    console.log('end', event);
});

foo.set(foo.toJSON());