如何克隆Ember Data记录,包括关系? [英] How can I clone an Ember Data record, including relationships?
本文介绍了如何克隆Ember Data记录,包括关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
belongsTo
/ hasMany
关系被克隆。如果我不知道有什么关系可以离开存在的关系,我可以这样做吗? 为了参考,这里是我已经这将克隆一个Ember Data记录的属性:
var attributeKeys = oldModel.get('constructor.attributes.keys.list') ;
var newRecord = this.get('store')。createRecord(oldModel.constructor.typeKey);
newRecord.setProperties(oldModel.getProperties(attributeKeys));
解决方案
对Daniel的 answer ,允许提供覆盖,并清除新记录的ID,以便安全。另外我也不想在克隆方法中调用 save
,而是将其留给调用者。
DS.Model.reopen({
clone:function(overrides){
var model = this,
attrs = model.toJSON(),
class_type = model.constructor;
var root = Ember.String.decamelize(class_type.toString()。split('。')[1]);
/ *
*需要用
*实际模型实例替换belongsTo关联(id)
*
*例如,如果belongsTo关联是项目,
* json项目的价值将是:(project:project_id_1)
*,这需要转换为(project:[projectInstance])
* /
this.eachRelationship(function(key,关系){
if(relationship.kind =='belongsTo'){
attrs [key] = model.get(key);
}
});
/ *
*需要将新记录与旧版本分开。
* /
删除attrs.id;
/ *
*如果提供覆盖,应用覆盖。
* /
if(Ember.typeOf(overrides)==='object'){
Ember.setProperties(attrs,overrides);
}
return this.store.createRecord(root,attrs);
}
});
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 this somehow if I don't know what relationships would be possible, going off of the relationships that exist?
For reference, here is what I've got that will clone an Ember Data record's attributes:
var attributeKeys = oldModel.get('constructor.attributes.keys.list');
var newRecord = this.get('store').createRecord(oldModel.constructor.typeKey);
newRecord.setProperties(oldModel.getProperties(attributeKeys));
解决方案
A few improvements to Daniel's answer that allows providing overrides, and clears the id for new records, to be safe. Also I prefer not to call save
within the clone method, but leave it up to the caller.
DS.Model.reopen({
clone: function(overrides) {
var model = this,
attrs = model.toJSON(),
class_type = model.constructor;
var root = Ember.String.decamelize(class_type.toString().split('.')[1]);
/*
* Need to replace the belongsTo association ( id ) with the
* actual model instance.
*
* For example if belongsTo association is project, the
* json value for project will be: ( project: "project_id_1" )
* and this needs to be converted to ( project: [projectInstance] )
*/
this.eachRelationship(function(key, relationship) {
if (relationship.kind == 'belongsTo') {
attrs[key] = model.get(key);
}
});
/*
* Need to dissociate the new record from the old.
*/
delete attrs.id;
/*
* Apply overrides if provided.
*/
if (Ember.typeOf(overrides) === 'object') {
Ember.setProperties(attrs, overrides);
}
return this.store.createRecord(root, attrs);
}
});
这篇关于如何克隆Ember Data记录,包括关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文