如何在Ember.js中销毁一个transition上的路由模型



在我的Ember应用程序中,我有两个路由,peopleperson

当我转换到person时,当前模型的值被绑定到应用程序控制器中的一个属性。

App.ApplicationController = Ember.Controller.extend({
  needs: [ 'person' ],
  currentPerson: Ember.computed('controllers.person.currentPerson', function () {
    var person = this.get('controllers.person.currentPerson');
    return person ? 'selected person #' + person.id : 'no one has been selected';
  })
});
App.PersonController = Ember.Controller.extend({
  currentPerson: Ember.computed.alias('model')
});

当我过渡到person路由时,我想清除该值,理想地破坏person模型。

我试过:

willTransition: function () {
  this.get('model').destroy();
}

但这不起作用。如何正确删除缓存的路由模型?

示例:http://emberjs.jsbin.com/xogati/1/edit?html、js、输出

谢谢!

willTransition钩子应该可以工作。根据您拥有的代码,看起来您可能错误地使用了它。willTransition是路由上的一个事件,但是你使用的是this.get('model'),并且路由上没有model属性(它在控制器上)。这里是你想要的完整代码,应该完成你需要的。

App.PersonRoute = Ember.Route.extend({
    actions: {
        willTransition: function(transition) {
            this.get('controller.model').destroy();
        }
    }
});

作为旁注,有很多奇怪的过渡,当他们被解雇(如果有的话)。如果你发现这在某些情况下对你不起作用,你可能需要看看deactivate钩子。

给那些偶然发现的人一个答案。

deactivate事件允许创建一个将拆除模型的事件处理程序。对于这个特殊的用例,我发现this.set('controller.model', null);完成了这项工作,但假设您有一个更复杂的模型(即ember-data模型),您将需要实现一些更多的逻辑。

destroyModel: function () {
  this.set('controller.model', null);
}.on('deactivate')

示例:http://emberjs.jsbin.com/xogati/5/edit?html、js、输出

感谢@GJK和@Artych。

为将来的读者提供一个提示,在这一点上,首选的方法如下:

在你的路由文件:

  actions: {
    willTransition() {
      const modelRecord = this.controller.get('model');
      // toss record changes (or the entire record itself) if it hasn't been saved
      if (modelRecord.get('hasDirtyAttributes')) {
        modelRecord.rollbackAttributes();
      }
    }
  }

通常建议在willTransition钩子中这样做,因为如果你只在deactivate钩子中这样做,并且你正在使用嵌套路由

最新更新