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

我已经发现我可以克隆Ember数据记录并复制其属性,但是没有任何belongsTo / hasMany关系被克隆.如果我不知道什么样的关系可能会脱离现有的关系,我能以某种方式这样做吗?

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

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

解决方法

Daniel’s 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]);

        /*
         * 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);
    }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


js中event的用法
js中能调用python吗
js中split的用法
js怎么设置边框样式
js中截取字符串的方法
js中innerhtml的用法
javascript的成熟分类方式有哪些
js中document是什么意思
js怎样让div中的文字居中
js中怎样定义一个对象
javascript的成熟分类介绍
js中parseint什么意思
js中字符串如何排序
void在js中是什么意思
js中如何定义函数
js中arguments是什么意思
js中什么是同步和异步
js中如何sleep一秒
js中ui函数是什么意思
js中如何遍历数组