ember.js – 如何克隆Ember数据记录,包括关系?

前端之家收集整理的这篇文章主要介绍了ember.js – 如何克隆Ember数据记录,包括关系?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经发现我可以克隆Ember数据记录并复制其属性,但是没有任何belongsTo / hasMany关系被克隆.如果我不知道什么样的关系可能会脱离现有的关系,我能以某种方式这样做吗?

作为参考,这里是我将克隆Ember数据记录的属性

  1. var attributeKeys = oldModel.get('constructor.attributes.keys.list');
  2. var newRecord = this.get('store').createRecord(oldModel.constructor.typeKey);
  3. newRecord.setProperties(oldModel.getProperties(attributeKeys));

解决方法

Daniel’s answer的一些改进允许提供覆盖,并清除新记录的id,以确保安全.此外,我不想在克隆方法调用save,而是将其留给调用者.
  1. DS.Model.reopen({
  2. clone: function(overrides) {
  3. var model = this,attrs = model.toJSON(),class_type = model.constructor;
  4.  
  5. var root = Ember.String.decamelize(class_type.toString().split('.')[1]);
  6.  
  7. /*
  8. * Need to replace the belongsTo association ( id ) with the
  9. * actual model instance.
  10. *
  11. * For example if belongsTo association is project,the
  12. * json value for project will be: ( project: "project_id_1" )
  13. * and this needs to be converted to ( project: [projectInstance] )
  14. */
  15. this.eachRelationship(function(key,relationship) {
  16. if (relationship.kind == 'belongsTo') {
  17. attrs[key] = model.get(key);
  18. }
  19. });
  20.  
  21. /*
  22. * Need to dissociate the new record from the old.
  23. */
  24. delete attrs.id;
  25.  
  26. /*
  27. * Apply overrides if provided.
  28. */
  29. if (Ember.typeOf(overrides) === 'object') {
  30. Ember.setProperties(attrs,overrides);
  31. }
  32.  
  33. return this.store.createRecord(root,attrs);
  34. }
  35. });

猜你在找的JavaScript相关文章