14
votes

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

2
emp.get('employee'); and your employee isn't an instance of the employee model, if you want an empty employee model use this.store.createRecord('employee', {});Patsy Issa
I tried emp.get('employee'), but is giving TypeError: emp.get is not a functionManu Benjamin
Miguel covered everything that needed to be covered ^^Patsy Issa
Yes Kitler. It worked for me. Thanks for helping.Manu Benjamin

2 Answers

32
votes

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.
1
votes
this.get('context')

gives you access to the model in the route action.