How to clone a backbone collection

前端 未结 4 541
遥遥无期
遥遥无期 2021-02-05 00:58

Is there a way to easily clone Backbone Collection? I wonder why there is no build in method like for models. My problem is that I have a model holding a collection of childs. W

4条回答
  •  不思量自难忘°
    2021-02-05 02:00

    What's your use case that you want to clone the collection?

    There isn't a built in clone function for a collection because you do not want to clone the models within the collection. Cloning a model would cause there to be two separate instances of the same model, and if you update one model, the other one won't be updated.

    If you want to create a new collection based upon a certain criteria, then you can use the collection's filter method.

    var freshmenModels = studentsCollection.filter(function(student) {
      return student.get('Year') === 'Freshman';
    }
    
    var freshmenCollection = new Backbone.Collection(freshmenModels);
    

    To go ahead and clone the models in the collection, you can write the following code

    var clonedCollection = new Backbone.Collection();
    studentsCollection.each(function(studentModel) {
      clonedCollection.add(new Backbone.Model(studentModel.toJSON()));
    });
    

提交回复
热议问题