Backbone-relational icon indicating copy to clipboard operation
Backbone-relational copied to clipboard

Collection instances share `options` object by reference which is unexpected

Open lukasmlady opened this issue 6 years ago • 0 comments

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.

https://github.com/PaulUithol/Backbone-relational/blob/1ee7dc05397f058063f6a10080bfeef18b20c6a5/backbone-relational.js#L932-L942

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

https://github.com/PaulUithol/Backbone-relational/blob/1ee7dc05397f058063f6a10080bfeef18b20c6a5/backbone-relational.js#L967-L977

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

lukasmlady avatar Mar 28 '18 17:03 lukasmlady