Backbone bootstrapped collection doesn't initialize correctly

前端 未结 2 1920
心在旅途
心在旅途 2021-01-12 23:14

I have an issue, that was really hard to notice, because for the most part everything works. It was only when I tried to manipulate my data in my collections initialize func

2条回答
  •  情深已故
    2021-01-12 23:54

    You are bootstrapping incorrectly. You will need to use the Collection reset() method, and listen for a reset event in your collecton like so

    Bootstrap code:

    var collection = new MyCollection;
    collection.reset();
    

    Your collection code:

    var MyCollection = Backbone.Collection.extend({
        model: MyModel,
    
        initialize: function() {
            this.on("reset", this.foobar);
        },
    
        foobar: function(collection) {
           console.log(this); // will be the same
           console.log(this.length); //  will equal 3
           this.each(function(model) {
               console.log(model); // will output a console for each model.
           });
        }
    
    });
    

提交回复
热议问题