Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember access model inside a controller

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'});
});
like image 431
Bogdan Zurac Avatar asked Jan 20 '15 14:01

Bogdan Zurac


People also ask

What is an ember controller?

In Ember. js, controllers allow you to decorate your models with display logic. In general, your models will have properties that are saved to the server, while controllers will have properties that your app does not need to save to the server.

What is an ember model?

In Ember Data, models are objects that represent the underlying data that your application presents to the user. Note that Ember Data models are a different concept than the model method on Routes, although they share the same name.

Is Ember an MVC framework?

Ember. js is a MVC (Model-View-Controller) JavaScript framework used to develop large client-side web applications. In comparison to other JavaScript MVC frameworks, it gives you the ability to write organized and structured code.


1 Answers

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

like image 95
Bogdan Zurac Avatar answered Oct 13 '22 00:10

Bogdan Zurac