Model for application route in ember.js

1.8k Views Asked by At

I have the following code where I am trying to set the model for ApplicationRoute but it doesn't seem to work. I have a few doubts regarding the Ember code. Firstly, Can I set a model for application route? Secondly, if the model for the route has fields named count and fileName, do I need to declare these fields in the controller also. It looks like if I do so, the value in the controller takes precedence over the model value. Also can I do something like this.set('total',5) in the setupController even though total isn't defined anywhere.

App.ApplicationRoute=Ember.Route.extend({
model:function(){
    console.log('model called');
    return {count:3,fileName:'Doc1'};
},
setupController:function(){
    console.log(this.get('model').fileName);
    this.set('count',this.get('model.count')); //Do I manually need to do this?
    this.set('fileName',this.get('model.fileName')); //Do I manually need to do this?
}
});
App.ApplicationController=Ember.Controller.extend({
    count:0,//Is this necessary?? Can I directly set the property with declaring it like this
    fileName:''
});
1

There are 1 best solutions below

1
On

You can do:

App.ApplicationController=Ember.Controller.extend({
    count: function(){
       return this.get('model').get('count');
    }.property('model.count')
});

So anytime model.count changes, the propery would get updated automatically.

And yep, you can set the model directly on the route. When you do this.set('total', 5) in the controller, you only set that property on the controller and not the model. In order to update the model, you would need to do:

var model = this.get('model');
model.set('total', 5);

Lastly, your setupController code isn't correct. Here is the sample method found on the Ember docs (located here):

App.SongRoute = Ember.Route.extend({
  setupController: function(controller, song) {
    controller.set('model', song);
  }
});