简体   繁体   English

Ember:你如何从路由器访问模型?

[英]Ember: how do you access the model from the router?

Based on what I've read (please correct me if I'm mistaken), the logic that handles when a model should be saved and where to transition next should be in the router. 基于我所读到的内容(如果我弄错了,请纠正我),处理模型应该保存的逻辑以及下一步转换的逻辑应该在路由器中。

If that is the case, I'm running into a bit of a problem: I don't know how to access the model from the route . 如果是这种情况,我遇到了一个问题: 我不知道如何从路线访问模型

This is my controller (and the console logs "CREATED" after I press submit): 这是我的控制器(并且在我按下提交后控制台记录“CREATED”):

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()

I should move that logic into the route, right? 我应该将这条逻辑移到路线上,对吗? Let's try that: 我们试试看:

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')

Note: I understand that the submit event bubbles up from the view, to the controller, then finally the route, stopping at any one of them that has "submit" defined. 注意:我知道提交事件从视图,控制器,然后最终路由起泡,停在任何一个已定义“提交”的路由。 So since I want the route to handle it, I removed the controller. 因此,我想要路由来处理它,我删除了控制器。 I'm able to see any console.log done in the route, I just need to be able to get to the model instance. 我能够在路径中看到任何console.log ,我只需要能够访问模型实例。

I'm using Ember v1.0.0-rc.5-7-g610589a 我正在使用Ember v1.0.0-rc.5-7-g610589a

Thanks! 谢谢!

Two options: this.currentModel or this.modelFor(routeName) 两个选项: this.currentModelthis.modelFor(routeName)

Update 更新

I spoke to Señor Alex Matchneer about this. 我和SeñorAlexMatchneer谈到了这件事。 There are no plans for this.currentModel to go away anytime soon, but he considers this.modelFor(this.routeName) the public API. this.currentModel没有计划很快就会消失,但他认为this.modelFor(this.routeName)是公共API。

应该做些什么

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

this.currentModel isn't really the approved way as described here this.currentModel实际上并不是这里描述的批准方式

but in my version of Ember (1.11) this.modelFor(this.routeName) returns null, so this is what worked for me 但在我的Ember版本(1.11)中, this.modelFor(this.routeName)返回null,所以这对我this.modelFor(this.routeName)

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

You could also use this.controller.get('model'); 你也可以使用this.controller.get('model'); but there are plans to remove the controller. 但有计划删除控制器。

Till that we can use the above code to retrieve the routes current model 直到我们可以使用上面的代码来检索当前模型的路线

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

const model = this.controller.model;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM