How can I clone an Ember Data record, including relationships?

后端 未结 4 1189
我在风中等你
我在风中等你 2021-02-09 04:45

I\'ve figured out that I can clone an Ember Data record and copy its Attributes, but none of the belongsTo/hasMany relationships are cloned. Can I do t

4条回答
  •  太阳男子
    2021-02-09 05:35

    Here is the simple way to clone your Ember Model with relationships. working fine.

    Create a Copyable mixin like,

    import Ember from 'ember';
    
    export default Ember.Mixin.create(Ember.Copyable, {
    
        copy(deepClone) {
          var model = this, attrs = model.toJSON(), class_type = model.constructor;
          var root = Ember.String.decamelize(class_type.toString().split(':')[1]);
    
          if(deepClone) {
              this.eachRelationship(function(key, relationship){
                  if (relationship.kind == 'belongsTo') {
                      attrs[key] = model.get(key).copy(true);
                  } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                      attrs[key].splice(0);
                      model.get(key).forEach(function(obj) {
                          attrs[key].addObject(obj.copy(true));
                      });
                  }
              });
          }
          return this.store.createRecord(root, attrs);
        }
    });
    

    Add the mixin in your model,

    Note: If you want to clone your child model then, you need to include the mixin in child model as well

    USAGE:

    1. With relationship : YOURMODEL.copy(true)

    2. Without relationship : YOURMODEL.copy()

提交回复
热议问题