Manu Benjamin
Manu Benjamin

Reputation: 997

Ember - How to get route model inside route action

Is it possible to access route model inside route action?

I am passing multiple objects inside a route model to template,

 model: function() {
    return {
        employeeList : this.store.findAll("employee"),
        employee : Ember.Object.create()
    }
}

From the route action I am want to modify the route model.employee. I tried the following, but I am not getting the object.

actions:{
    editAction : function(id) {
        var emp = this.get("model");
        console.log(emp.employee);

    }
}

Can anyone give a solution to get and modify model object(employee)?

Upvotes: 15

Views: 9078

Answers (2)

steve_gallagher
steve_gallagher

Reputation: 3888

this.get('context')

gives you access to the model in the route action.

Upvotes: 1

miguelcobain
miguelcobain

Reputation: 4754

First problem is that you should return a promise from the model hook. That way, the transition will wait for the promise to Resolve. return { /*...*/}; returns an object and not a promise, even if the object itself contains promises. The solution is to use Ember.RSVP.hash like:

model() {
  return Ember.RSVP.hash({
    employeeList: this.store.findAll('employee'),
    employee: Ember.Object.create()
  });
}

This will return a promise that resolves when all inner promises resolve.


The second problem is that you can't use this.get('model') in a route. If you think about it the model property is the hook itself and not the resolved model. Solutions:

  1. That action is sent from the controller/template. Can't you pass the model as a parameter? That way you could access the model through the function arguments.
  2. If you absolutely need to, this.modelFor(this.routeName); returns the model for the current route.
  3. You can access the model in route through the controller like this.controller.get('model').
  4. You could also implement the setupController hook and access there the model. You can then do things like this.set('employeeModel', model); for later access.

Upvotes: 33

Related Questions