Ember克隆模型为新记录 [英] Ember clone model for new record

查看:84
本文介绍了Ember克隆模型为新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要克隆当前正在编辑的模型。

I want to make a clone of a model currently being edited.

我发现几种方法几乎可以工作。但是两者都不是完美的。

I've found a couple of ways that almost work. But neither are perfect.

1) model.get('data.attributes')对于camelCase形式的关系,生成一个新的记录,但是当然也缺少关系。

1) model.get('data.attributes') gets all the attributes except for relationships in camelCase form, generates a new record fine but the relationships are missing of course.

2) model.serialize()生成一个包含关系的所有属性的JSON对象。但是,由于对象不是camelCased( first_name )的属性将不被处理,所以 createRecord 不会很好处理

2) model.serialize() generates a JSON object, with all attributes including relationships. But createRecord will not handle it well since the object is not camelCased (attributes with underscores like first_name will not be handled)

创建克隆之后,我想要 transaction.createRecord(App.Document,myNewModelObject)更改/设置一些属性,最后是 commit()。任何人都有一些洞察力如何做到这一点?

After my clone has been created I want to transaction.createRecord(App.Document, myNewModelObject) change/set a couple of attributes and finally commit(). Anyone have some insight in how to do this?

推荐答案

这是一个更新的答案,它仍然不处理 hasMany 关系。

Here's an updated answer, it still doesn't handle hasMany relationships.

cloneBelongsTo: function(fromModel, toModel) {
  var relationships;
  relationships = Em.get(fromModel.constructor, 'relationships');
  return relationships.forEach(function(relationshipType) {
    var _relType;
    _relType = relationships.get(relationshipType);
    return _relType.forEach(function(relationship) {
      var name, relModel;
      relModel = Em.get(fromModel, relationship.name);
      if (relationship.kind === 'belongsTo' && relModel !== null) {
        name = relationship.name;
        return toModel.set(name, fromModel.get(name));
      }
    });
  });
}

这是我如何使用它:

// create a JSON representation of the old model
var newModel = oldModel.toJSON();
// set the properties you want to alter
newModel.public = false;
// create a new record
newDocument = store.createRecord('document', newModel);
// call the cloneBelongsTo method after the record is created
cloneBelongsTo(model, newDocument);
// finally save the new model
newDocument.save();

这篇关于Ember克隆模型为新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆