Marionette CompositeView children.findByIndex not working as expected after collection sync

后端 未结 1 988
失恋的感觉
失恋的感觉 2021-01-27 18:52

I have the following code that happens after a collection sync:

    adGeneration: function() {
        var child = this.children.findByIndex(this.childr         


        
相关标签:
1条回答
  • 2021-01-27 19:15

    I think your problem is in the ProductsCollection.loadMore method. There, in the success callback to your fetch you do,

    function(collection) { this.add(collection); }
    

    What's happening behind the scenes is that before your success callback is invoked, Backbone will first run Collection.set() on your data. By default, inside set your data will be parsed into a array of models returned by ProductsCollection.parse and if any new models are found they will be add'ed to your existing collection (note that unless you pass { remove: false } to your fetch options, models in your collection which are not in your last fetch will be removed. See Collection.set)

    So, what happens when you do the fetch in loadMore, which is called after the first fetch, Backbone will first add all the models from the server (that are returned from ProductsCollection.parse) and then invoke the success callback of your fetch, which, essentially does one last add. And what it's add'ing is the ProductsCollection instance. Not collection.models, an array of models, rather a Backbone object that has a property models that holds a raw array of models. Hence, the strange output:

    Object {length: 40, models: Array[41], _byId: Object, _listeningTo: Object, 
    _listenId: "l14"…}
    

    Simply remove that success callback (which is unnecessary) and the last child view of your ProductsView should be the view rendered from the last model returned.

    0 讨论(0)
提交回复
热议问题