【问题标题】:How to destroy a route model on transition in Ember.js如何在 Ember.js 中销毁转换时的路由模型
【发布时间】:2015-07-10 13:38:48
【问题描述】:

在我的 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,output

谢谢!

【问题讨论】:

标签: javascript ember.js


【解决方案1】:

willTransition 钩子应该可以工作。根据您拥有的代码,您可能使用不正确。 willTransition 是路线上的一个事件,但您使用的是 this.get('model') 并且路线上没有 model 属性(它在控制器上)。这是您想要的完整代码,应该可以满足您的需求。

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

作为旁注,过渡以及何时被触发(如果有的话)有很多古怪之处。如果您发现在某些情况下这对您不起作用,您可能需要查看 deactivate 挂钩。

【讨论】:

  • 似乎不起作用,但 deactivate 挂钩可能会有所帮助。谢谢!
  • 这似乎实现了我想要的,但我不确定这是不是最好的方法。 destroyModel: function () { this.set('controller.model', null); }.on('deactivate')
【解决方案2】:

给任何偶然发现此问题的人留下答案。

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,output

感谢@GJK 和@Artych。

【讨论】:

    【解决方案3】:

    作为对未来读者的说明,目前首选的方法如下:

    在您的路线文件中:

      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 挂钩中执行此操作并且您使用的是嵌套路由,则会遇到障碍

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 2015-04-15
      • 2016-05-11
      相关资源
      最近更新 更多