Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lukasmlady opened this issue Mar 28, 2018 · 0 comments

Comments

@lukasmlady
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant