ember.js – 删除与ember-data相关联的模型

我有两个型号:
App.User = DS.Model.create({
  comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.create({
  user: DS.belongsTo('App.User')
});

用户删除时,它也会删除其后端的所有注释,所以我应该从客户端身份映射中删除它们.

我从另一个地方列出系统上的所有评论,所以在删除用户之后,它将会崩溃.

有没有办法在协会上指定这种依赖关系?谢谢!

解决方法

当我想实现这个行为时,我使用mixin.我的模型定义如下:
App.Post = DS.Model.extend(App.DeletesDependentRelationships,{
    dependentRelationships: ['comments'],comments: DS.hasMany('App.Comment'),author: DS.belongsTo('App.User')
});

App.User = DS.Model.extend();

App.Comment = DS.Model.extend({
    post: DS.belongsTo('App.Post')
});

mixin本身:

App.DeletesDependentRelationships = Ember.Mixin.create({

    // an array of relationship names to delete
    dependentRelationships: null,// set to 'delete' or 'unload' depending on whether or not you want
    // to actually send the deletions to the server
    deleteMethod: 'unload',deleteRecord: function() {
        var transaction = this.get('store').transaction();
        transaction.add(this);
        this.deleteDependentRelationships(transaction);
        this._super();
    },deleteDependentRelationships: function(transaction) {
        var self = this;
        var klass = Ember.get(this.constructor.toString());
        var fields = Ember.get(klass,'fields');

        this.get('dependentRelationships').forEach(function(name) {
            var relationshipType = fields.get(name);
            switch(relationshipType) {
                case 'belongsTo': return self.deleteBelongsToRelationship(name,transaction);
                case 'hasMany': return self.deleteHasManyRelationship(name,transaction);
            }
        });
    },deleteBelongsToRelationship: function(name,transaction) {
        var record = this.get(name);
        if (record) this.deleteOrUnloadRecord(record,transaction);
    },deleteHasManyRelationship: function(key,transaction) {
        var self = this;

        // deleting from a RecordArray doesn't play well with forEach,// so convert to a normal array first
        this.get(key).toArray().forEach(function(record) {
            self.deleteOrUnloadRecord(record,transaction);
        });
    },deleteOrUnloadRecord: function(record,transaction) {
        var deleteMethod = this.get('deleteMethod');
        if (deleteMethod === 'delete') {
            transaction.add(record);
            record.deleteRecord();
        }
        else if (deleteMethod === 'unload') {
            var store = this.get('store');
            store.unloadRecord(record);
        }
    }
});

请注意,您可以通过deleteMethod指定是否要将DELETE请求发送到您的API.如果您的后端配置为自动删除相关记录,则需要使用默认值.

这是一个jsfiddle显示它在行动.

相关文章

事件冒泡和事件捕获 起因:今天在封装一个bind函数的时候,发现el.addEventListener函数支持第三个参数...
js小数运算会出现精度问题 js number类型 JS 数字类型只有number类型,number类型相当于其他强类型语言...
什么是跨域 跨域 : 广义的跨域包含一下内容 : 1.资源跳转(链接跳转,重定向跳转,表单提交) 2.资源...
@ "TOC" 常见对base64的认知(不完全正确) 首先对base64常见的认知,也是须知的必须有...
搞懂:MVVM模式和Vue中的MVVM模式 MVVM MVVM : 的缩写,说都能直接说出来 :模型, :视图, :视图模...
首先我们需要一个html代码的框架如下: 我们的目的是实现ul中的内容进行横向的一点一点滚动。ul中的内容...