Skip to content

Collection instances share options object by reference which is unexpected #584

@lukasmlady

Description

@lukasmlady

Minimal case showing the problem

Following is a test case that proves the equality in a minimalistic case:

const Child = Backbone.RelationalModel.extend();
const Children = Backbone.Collection.extend({ model: Child });
const Parent = Backbone.RelationalModel.extend({
  relations: [{
    type: Backbone.HasMany,
    key: 'children',
    relatedModel: Child,
    relatedCollection: Children
  }]
});

const parent1 = new Parent({ id: 'parent1', children: [{ id: 'child1' }] });
const parent2 = new Parent({ id: 'parent2', children: [{ id: 'child2' }] });

// This is how it is, though not really expected.
expect(parent1.get('children').options).to.equal(parent2.get('children').options);

Potential cause

In the following snippet, collectionOptions gets assigned an empty object, once when loading the library.

module.HasMany = module.Relation.extend({
collectionType: null,
options: {
reverseRelation: { type: 'HasOne' },
collectionType: module.Collection,
collectionKey: true,
collectionOptions: {}
},
initialize: function( opts ) {

That object is then reused and passed (in the case it is not a function) as options when instantiating a new collection.

_prepareCollection: function( collection ) {
if ( this.related ) {
this.stopListening( this.related );
}
if ( !collection || !( collection instanceof module.Collection ) ) {
var options = _.isFunction( this.options.collectionOptions ) ?
this.options.collectionOptions( this.instance ) : this.options.collectionOptions;
collection = new this.collectionType( null, options );
}

This most likely leads to instances of collections sharing a reference to the very same this.options object.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions