Backbone JS deep cloning of model and collection  

by ne on 2020-12-02 under Javascript

Backbone JS is a fantastic library when it comes to handy utility methods. It was indeed one of the pioneer javascript frameworks which aimed towards implementing MVP design pattern.

If you are more into the imperative coding style rather than the declarative programming style (example: Angular js), then you might love backbone js.

Very often we come across a use case where we need to deep clone an existing collection in backbone. Deep Cloning is a technique of copying the entire collection, along with copy of all the referenced objects present in the collection. So, after a deep clone operation, the collection returned can no way modify the original data structure, leaving the two collections mutual exclusive.

We will extend the backbone API to enrich it with 2 new methods, one for returning deep cloned model object, and another to return a deep cloned copy of collection-of-models.

 

Cloning Model



    Backbone.Model.prototype.deepClone = function () {
        var clonedObject, key, cid = this.cid;
        clonedObject = new this.constructor(this.attributes);
        clonedObject.cid = cid;
        for (key in clonedObject.attributes) {
            if (clonedObject.attributes.hasOwnProperty(key)) {
                if (clonedObject.attributes[key] instanceof Backbone.Collection) {
                    clonedObject.attributes[key] = clonedObject.attributes[key].deepClone();
                }
                else if (clonedObject.attributes[key] instanceof Backbone.Model) {
                    clonedObject.attributes[key] = clonedObject.attributes[key].deepClone();
                }
            }
        }
        return clonedObject;
    };

 

Cloning Collection

Now utilizing the above method, Here's an extension method, which will extend the backbone API, and will add the following method in the API for you.

 



Backbone.Collection.prototype.deepClone = function () {
    return new this.constructor(_.map(this.models, function (m) {
        return m.deepClone();
    }));
};

Now you can call the deepClone method from backbone API, and can expect it to return a new mutually exclusive deep cloned object.