AmpersandJS / ampersand-filtered-subcollection

Filterable, sortable, proxy of a collection that behaves like a collection.
MIT License
11 stars 7 forks source link

Change events are bubbled from parent collection even if the state is not in subcollection #15

Closed herkyl closed 9 years ago

herkyl commented 9 years ago

I stumbled on weird behaviour using this module and don't know if it is intended or a bug but since it did not work like this in ampersand-subcollection I guess it's a bug.

When changing an element in the parent collection (that is not in the subcollection) the subcollection triggers a change event.

This is problematic if you have a huge collection of items, that are filtered into smaller subcollections. When doing a change in one of the subcollections a change event is triggered in all of the other subcollections as well.

Here is the code to test this:

var AmpersandState = require('ampersand-state');
var AmpersandCollection = require('ampersand-collection');
var FilteredSubcollection = require('ampersand-filtered-subcollection');

var State = AmpersandState.extend({
  props: {
    n: 'number'
  }
});

var Collection = AmpersandCollection.extend({
  model: State
});

var collection = new Collection([
  new State({n: 0}),
  new State({n: 9})
]);

var subCollection = new FilteredSubcollection(collection, {
    where: {
      n: 0
    }
});

subCollection.on('change', function () {
  console.log('Change in subCollection');
});

collection.on('change', function () {
  console.log('Change in collection');
});

console.log({
  'subCollection.length': subCollection.length,
  'collection.length': collection.length,
});

collection.models[1].n = 10;  // change the state not in any subcollections

console.log({
  'subCollection.length': subCollection.length,
  'collection.length': collection.length,
});