防止ArrayController添加验证失败的模型 [英] Prevent an ArrayController from adding a model which failed validation

查看:75
本文介绍了防止ArrayController添加验证失败的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

工作流程是:


  1. 用户位于新页面。

  2. 点击保存,导致模型验证失败。显示与模型绑定的错误。仍然在同一页面上。

  3. 用户现在导航到索引页面,并看到添加到列表中的无效记录。

ArrayController似乎添加了无效验证的记录。

The ArrayController seems to be adding records which failed validations.

App.CompaniesNewRoute = Ember.Route.extend({

    model: function(){
      var company = App.Company.createRecord();
      this.wireObservers(company, this);
      return company;
    },

    events: {
      save: function(){
        var controller = this.controllerFor(this.routeName);
        controller.get('transaction').commit();
      }
    },

   wireObservers: function(company, router) {
     company.on('becameInvalid', function(record){
      // do something to remove it from the arraycontroller
      // record.rollback();
     });

     company.on('didCreate', function(){
       router.transitionTo('companies.index')
     });
   })
})

becomeInvalid 事件确实被调用。执行 record.rollback()抛出异常:

The becameInvalid event does get called. Doing a record.rollback() throws an exception:

Uncaught Error: Attempted to handle event `becameClean` on     <App.Company:ember612:null> while in state rootState.loaded.created.invalid. Called with undefined ember-data.js:3495
DS.StateManager.Ember.StateManager.extend.unhandledEvent ember-data.js:3495

有没有办法阻止ArrayController添加无效验证的记录。

Is there a way to prevent ArrayController to add records which failed validation.

推荐答案

尝试通过商店回滚交易。

Try to rollback the transaction through the store instead.

   wireObservers: function(company, router) {
     var _self = this;
     company.on('becameInvalid', function(record){
      // do something to remove it from the arraycontroller
       _self.store.rollback();
     });

     company.on('didCreate', function(){
       router.transitionTo('companies.index')
     });
   })

您应该考虑为此目的创建一个特定的事务,而不是使用默认一。要在路由中创建一个新的事务,您可以执行以下

You should consider creating a specific transaction for the purpose rather than using the default one. To create a new transaction inside a route, you can do the following

App.MyRoute = Ember.Route.extend({
    transaction: this.store.transaction();
})

然后创建您的记录并使用

and then create your record and add it to the transaction using

var company = this.transaction.createRecord(App.Company);

,最后提交或回滚事务

this.transaction.commit();
this.transaction.rollback();

这篇关于防止ArrayController添加验证失败的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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