Al78
Al78

Reputation: 41

how controller, model and router work together in ember?

I am confused how controller, model and router work together in ember? Is it possible to demonstrate this through example?

What is this model defined in route, what is its relation to this model 'app/models/someModel.js'?

app/routes/someRoute.js:

    export default Ember.Route.extend({
       model: function() {
         return something;
    }

Thanks

Upvotes: 3

Views: 57

Answers (1)

Saba
Saba

Reputation: 3666

Ember works on naming conventions. Routers set the value returned by its model function into controller's property model. So if you write this.get('model') in controller you will see the returned value by router's model function.

Further, if you want to have your route's model to take a particular form, you will want to map it to an defined object.

App.SomeModel = Ember.Object.extend({
    firstName : '',
    lastName : '',

    fullName: function () {
       return this.get('firstName' + " " + this.get('lastName');
    }.property('firstName', 'lastName'),

    birthdate: function () {
       return moment(this.get('birth_date').format('MMMM Do YYYY');
    }.property('birth_date')
});

Now suppose the data from backend is in the following format:

{
  "firstName" : "PQR",
  "lastName" : "KLM",
  "birth_date" : "15 Oct 1992"
}

So the router will be

App.SomeRoute = Ember.Route.extend({
     model : function () {
         var promise = $.get('person.json');
         return promise.then(function (response) {
            return App.SomeModel.create(response); //Here response will be the JSON above.
         });
     }
});

Upvotes: 1

Related Questions