【问题标题】:What's the best approach to "force" the model hook to fire?“强制”模型钩子开火的最佳方法是什么?
【发布时间】:2013-12-01 20:37:42
【问题描述】:

我使用的是 ember.js 1.2,我的一条路线有一个非常动态的模型。当我第一次跳入路由或粘贴 url 时,路由的模型钩子会触发,然后设置控制器触发并且一切都按预期工作。

当我稍后进入路由时(但不是直接从 url 进入)时会出现问题 - 这只会命中 setupController 钩子(并且模型方法永远不会触发)。但从技术上讲,改变的是 url(和父模型)。而对于这个模型,它主要是从父模型定义的(使用该父模型在运行时获取一组新的动态配置)。

那么,每次加载此特定路由时,如何强制 setupController 重新执行模型挂钩? (好像模型方法每次都在触发)。

或者...我应该在 setupController 中获取这个动态模型,并通过让它返回一个空对象来保持模型钩子逻辑少吗?

更新

App.ChildIndexRoute = Ember.Route.extend(App.ModelMixin, {
  setupController: function(controller, model) {
    this._super(controller, model);
    var parent = this.modelFor('parent');
    return this.getForParent(parent).then(function(things) {
      controller.set('model', things);
    });
  }
});

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    您可以使用setupController hook 代替模型挂钩,这是一种完全可以接受的处理方式。

    从技术上讲,转换是调用模型钩子并将其提供给 setupController。

    在链条中的哪个位置没有触发模型钩子?这是一个包含一些嵌套资源的简单应用。

    http://emberjs.jsbin.com/AtebAsOS/6/edit

    本例中的关键代码在 DogsRoute 中:

    App.DogsRoute = Em.Route.extend({
      setupController: function(controller, model){
        model = Em.get(this.modelFor('cow'), 'dogs');
         this._super(controller, model); 
      }
    });
    

    来自文档:

    [setupController] 方法由控制器调用,用于当前路由和model 钩子提供的模型。

    因此,当您使用获取的狗模型覆盖模型并将其传递给 _super 时,控制器将使用新获取的模型。

    【讨论】:

    • 您将如何处理通过查询参数中的动态段获取狗? model 钩子接受参数,但 setupController 不接受。像这样从模型的 id 中获取(强制刷新模型):model = App.MyModel.fetch(model.get('id')); this._super(controller, model); 似乎对我不起作用。我看到 POST 请求发生了,但视图上的字段是空白的。
    • 这种设置模型的方式是否与查询参数一起使用 resfreshModel 自动刷新模型?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多