I had to implement copy functionality in our Ember application so it would allow to copy any section of data from parent source to target. In order for this to work deep copy of corresponding section has to be created and each id changed in it so that Ember handles it as another entity.

In Ember you can add Copyable  mixin to your object and then implement method copy(). That’s fine, but what if you want to make it generic for anything? Other approach we all know is deep copy by serialization/deserialization.

If you are using Ember Data it is likely that you have your own serializer and adapter. So in order to implement deep copy you will need a bit of “magic”. Here it is:

copySection: function(source, target, sectionName){
    var sourceSection = source.get(sectionName);
    var copiedSection = sourceSection.serialize();
    var type = source.constructor.metaForProperty(sectionName).type;
    var serializer = this.store.serializerFor(type.typeKey);

    // traverse your copiedSection and generate new ID for each child

    var normalized = serializer.extractSingle(this.store, type, copiedSection, copiedSection.id, 'findById');
    var deserialized = this.store.push(type, normalized);
    target.set(sectionName, deserialized);

Hope it comes handy for someone.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone