简体   繁体   中英

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

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.

I'm using Ember v1.0.0-rc.5-7-g610589a

Thanks!

Two options: this.currentModel or this.modelFor(routeName)

Update

I spoke to Señor Alex Matchneer about this. There are no plans for this.currentModel to go away anytime soon, but he considers this.modelFor(this.routeName) the public API.

应该做些什么

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

this.currentModel isn't really the approved way as described here

but in my version of Ember (1.11) this.modelFor(this.routeName) returns null, so this is what worked for me

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

You could also use 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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