AmpersandJS / ampersand-state

Core state management object.
MIT License
141 stars 75 forks source link

Can't hook into child collection initialization via initialize or events #92

Open mmacaula opened 10 years ago

mmacaula commented 10 years ago

I have a child collection declared in a State. RequireBin runnable code here. I'd like to be able to initialize my collection with what is being inflated from the parent but can't seem to find a hook into doing it. I'd expect either the models on initialize, or a reset or a lot of add events, but State initializes an empty collection first and then silently resets the collection with the actual passed in models.


var State = require('ampersand-state');
var Collection = require('ampersand-collection');

var ChildModel = State.extend({});
var ChildCollection = Collection.extend({
  model : ChildModel,
  initialize : function(models){
    // models is empty
    if(models.length > 0){
        alert('inialize never called with any models');
    }
    this.on('reset', function(models){
      // this never gets called
      alert('reset never called');
    });
    this.on('add', function(model){
      // this never gets called
      alert('add never called');
    });
  }
});

var Parent = State.extend({
  collections : {
    childCollection : ChildCollection
  }
});

var parent = new Parent({childCollection : [ {}, {}]});
alert('parent constructed children: ' + parent.childCollection.length);

Is there a way to change this so I can hook into my child collection's initialize? Currently I'm stuck doing something like this:

var Parent = State.extend({
  collections : {
    childCollection : ChildCollection
  },
  initialize : function(){
    this.childCollection.doInitializationWork();
  }
});

My initial thought is to not pass {silent: true} when the child is first populated via reset, but I'm not sure how that might affect other tests. I'd be happy to contribute (with tests!) a solution if there is a need for a code change. Thanks and awesome job with Ampersand!

lukekarrys commented 10 years ago

Hey @mmacaula, I ran into a similar issue over at #90. I'm also not sure my fix there is 100% the right one. Can you test your use case with that branch and see if you get the expected behavior?

Basically it passes {silent: false} down to child collections during initialization so that they get the proper add events. In the meantime in my app I've just been putting {silent: false} in the options whenever I fetch or init a model or collection with children.

mmacaula commented 10 years ago

Thanks @lukekarrys yes I think this definitely being addressed there. I'll close this one assuming a solution will be found in that issue