How to clone a backbone collection

前端 未结 4 546
遥遥无期
遥遥无期 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 01:37

    Another option, if you need the following (which is what I was looking for when I found this question ;) ):

    • The copy of the collection should be of the same type as the original collection (e.g. you've created your own collection type that extends Backbone.Collection)
    • The copy of the collection should be created with the same options as the original
    • The models in the copy of the collection should be created using the model.clone() method

    Code:

    var models = original.map(function (model) { return model.clone(); });    
    var options = _.clone(original.options);    
    var copy = new original.constructor(models, options);
    

    A generic clone method on Backbone.Collection would be awkward because there are always going to be subtleties around whether models and their nested objects get copied by reference or are themselves cloned. Requirements will vary wildly according to your scenario, so it's been left for you to write what you need.

提交回复
热议问题