9
votes

How can a model be accessed from within a controller ? Currently using the below code returns a "undefined is not a function" (go figure JS fail...).

models/plan.js

import DS from 'ember-data';

export default DS.Model.extend({
    name:       DS.attr('string'),
    period:     DS.attr('number'),
    price:      DS.attr('number'),
});

routes/checkout.js

import Ember from 'ember';

export default Ember.Route.extend({

    model: function(params) {
        return this.store.find('plan', params.plan_id);
    }
});

controllers/checkout.js

import Ember from 'ember';

export default Ember.Controller.extend({

    submitPayment: function(error, result)
    {
          var plan = this.get('model');
    }
}

router.js

Router.map(function() {
  this.route('checkout', {path: '/checkout/:plan_id'});
});
1
maybe 'this' is not the controller in 'submitPayment'. Is submitPayment an action? If so you should put it inside an actions object. Or checkout the usuals, is model being fetched in the model hook? - blessenm
submitPayment is just a function being called from within an action. Yes, the model is being stored, no problems there. - Bogdan Zurac
Instead of extending 'Ember.Controller', try 'Ember.ObjectController'. - blessenm
No difference. Altough if I user this.get('model') inside the action instead of the function from above, I get an object. It has only the id set however, instead of all the fields. Why is that ? Also, if I use this.get('model.price') I get the actual price. So how can I get the entire model inside a single variable ? - Bogdan Zurac
Im not that familiar with ember data. You might need to call this.get('model').toJSON() - blessenm

1 Answers

11
votes

I've figured it out eventually. plan = this.get('model') works for the action. It returns the model, and the properties can be accessed with plan.get('price'). Not ideal, but it gets the job done. Why it didn't work is because it was inside a function that was called as a callback from inside the action. So probably the scope of "this" wasn't carried out to the callback function as well. I moved the callback function as an inner function inside the action, then "this" scope worked.

As for the scope problem, here's the solution setting an application controller variable to results returned from AJAX call