【问题标题】:Ember: how do you access the model from the router?Ember:你如何从路由器访问模型?
【发布时间】:2013-06-12 00:19:50
【问题描述】:

根据我读到的内容(如果我弄错了,请纠正我),处理何时保存模型以及下一步转换到哪里的逻辑应该在路由器中。

如果是这样的话,我遇到了一个问题:我不知道如何从路由访问模型

这是我的控制器(在我按下提交后控制台会记录“已创建”):

App.ScoutsNewController = Ember.ObjectController.extend
  submit: ->
    model = @get('model')
    model.on 'didCreate', ->
      console.log 'CREATED' # I want to  redirect to the index after creation
    model.save()

我应该将该逻辑移到路由中,对吗?让我们试试吧:

App.ScoutsNewRoute = Ember.Route.extend
  model: ->
    App.Scout.createRecord()

  events:
    submit: ->
      # Based on what I've read, the right place to put the code you see in the controller is here. How do I get access to the model?
      # I have tried @get('model'), @get('content')

注意:我知道提交事件从视图冒泡到控制器,最后是路由,在其中任何一个定义了“提交”的地方停止。因此,由于我希望路由处理它,因此我删除了控制器。我可以看到路由中完成的任何console.log,我只需要能够到达模型实例。

我正在使用Ember v1.0.0-rc.5-7-g610589a

谢谢!

【问题讨论】:

    标签: ember.js coffeescript


    【解决方案1】:

    对于 Ember 3.0.0,这是一种适用于我的文档化方式:

    const model = this.controller.model;
    

    【讨论】:

      【解决方案2】:

      您也可以使用this.controller.get('model');,但我们计划移除控制器。

      直到我们可以使用上面的代码来检索当前模型的路由

      【讨论】:

        【解决方案3】:

        两个选项:this.currentModelthis.modelFor(routeName)

        更新

        我就此与 Señor Alex Matchneer 进行了交谈。 this.currentModel 没有计划很快消失,但他认为 this.modelFor(this.routeName) 是公共 API。

        【讨论】:

        • 谢谢!看起来我最终会得到 currentModel。你是怎么知道的?似乎在文档中找不到它。
        • 我在代码库的那一部分工作过很多次。您会考虑打开 PR 将其添加到文档中吗?做起来不难,如果你需要帮助,我可以指导你。
        • 当然。立即克隆网站!
        • 我真的应该使用this.currentModel吗?缺乏文档以及它仅在私有方法github.com/emberjs/ember.js/blob/v1.0.0/packages/ember-routing/… 中设置的事实让我认为它不适合我使用。总是使用 this.modelFor(routeName) 代替?
        • 我就此与 Señor Alex Matchneer 进行了交谈。没有计划让 this.currentModel 很快消失,但他认为 this.modelFor(this.routeName) 是公共 API。
        【解决方案4】:

        this.currentModel 并不是here 所描述的真正认可的方式

        但在我的 Ember (1.11) 版本中,this.modelFor(this.routeName) 返回 null,所以这对我有用

        this.controllerFor(this.routeName).get('model')
        

        【讨论】:

          【解决方案5】:

          应该做的是

          this.controllerFor('ScoutsNew').get('content')
          

          【讨论】:

          猜你喜欢
          • 2014-06-10
          • 1970-01-01
          • 1970-01-01
          • 2018-01-04
          • 1970-01-01
          • 1970-01-01
          • 2012-12-19
          • 2013-01-26
          • 2015-05-12
          相关资源
          最近更新 更多