0

在我的控制器中,我打开了操作。此操作应删除模型的所有记录,然后发送 ajax 请求并获取新模型并替换模型。我的 ember 数据适配器是LSA

OlapApp.OpenController = Ember.Controller.extend({
needs: ['application'],
actions: {
    open: function() {
        var self = this;
        var xhr = $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: 'http://localhost:9095/service.asmx/getModel',
            data: '{}',
            success: function(response) {
                //Success Empty AxisModel;
                var data = JSON.parse(response.d);
                self.store.findAll('axisModel').then(function(items) {
                    console.log('try to delete');
                    items.forEach(function(item) {
                        item.deleteRecord();
                        item.save();
                    });
                });

                setTimeout(function() {
                    //Fill Axis Model
                    _.each(data.axisModel, function(v, i) {
                        var record = self.store.createRecord('axisModel', {
                            id: v["id"],
                            uniqueName: v["uniqueName"],
                            name: v["name"],
                            hierarchyUniqueName: v.hierarchyUniqueName,
                            type: v["type"],
                            isMeasure: v.isMeasure,
                            orderId: v.orderId,
                            isActive: v.isActive,
                            isAll: v.isAll,
                            sort: v.sort
                        });
                        record.save();
                    });
                    self.get('controllers.application').send('showNotification',     'Open', 'success');

                }, 2000);
            }
        });
    }
}
});

但是当我尝试创建一个新模型时,我得到了这个错误:

Assertion failed: The id a12 has already been used with another record of type OlapApp.AxisModel. 
Assertion failed: The id a13 has already been used with another record of type OlapApp.AxisModel. 

解决方案

最后我找到了解决方案。解决这个问题只需将 deleteRecord() 包装在 Ember.run.once 中,如下所示:

self.store.findAll('axisModel').then(function(items) {
                    items.forEach(function(item){
                          Ember.run.once(function(){
                           item.deleteRecord();
                         item.save();
                         });
                    });
                });
4

1 回答 1

2

对于删除记录,使用forEach会出现问题,因为对存储的查找结果是一个实时数组。您可以在 GitHub https://github.com/emberjs/data/issues/772中查看此讨论。您可以使用 toArray() 来制作实时数组的静态副本)

self.store.findAll('axisModel').then(
    function(items) {
            items.toArray().forEach(function(item){
                item.deleteRecord();
                item.save();
            });
        });
于 2013-11-06T11:03:56.867 回答