正确清理代码

dag*_*da1 19 coffeescript ember.js ember-data

我有以下两个编辑和新路线:

WZ.ExercisesNewRoute = Em.Route.extend
  model: ->
    WZ.Exercise.createRecord()
  deactivate: ->
    @_super.apply this, arguments
    @get('currentModel.transaction').rollback()

WZ.ExercisesEditRoute = Em.Route.extend
  model: (params) ->
    WZ.Exercise.find(params.exercise_id)
  serialize: (params, options) ->
    exercise_id: params.get('id')
  deactivate: ->
    @_super.apply this, arguments
    tx = @get('currentModel.transaction')
    tx.rollback() if tx
Run Code Online (Sandbox Code Playgroud)

我想知道在每次取消激活时应该使用正确的代码,以便在用户不保存,保存或其他任何情况下,存储处于正确的状态.

目前,如果我路由到编辑路线,然后直接到新路线而不保存,我收到以下错误:

未捕获错误:willSetProperty在状态rootState.deleted.saved中尝试处理事件.使用{reference:[object Object]调用,存储:,name:name}

Cor*_*ken 1

这个问题适用于较旧版本的 ember 数据,但答案是首先检查 isDeleted 的状态,只有在记录尚未删除时才回滚。

在较新的 ember 数据中,没有事务的概念,但如果您尝试回滚尚未持久化的记录,您仍然可能会遇到类似的问题。

我可能会在路由器 willTransition 事件中执行此操作,因为如果您想为用户提供保存更改的选项,您可以执行诸如中止转换之类的操作。

  willTransition: function(transition) {
    controller = this.get('controller')
    if( controller.get('content.isDirty') ) {
     if( controller.get('content.isNew') && confirm('Closing this window will revert all unsaved changes.') ){
       controller.get('content').deleteRecord();
     } else {
       controller.get('content').rollback()
     }
    }
  }
Run Code Online (Sandbox Code Playgroud)