JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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);
    }
});

大佬总结

以上是大佬教程为你收集整理的ember.js – 如何克隆Ember数据记录,包括关系?全部内容,希望文章能够帮你解决ember.js – 如何克隆Ember数据记录,包括关系?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。