2014-05-15 22 views
1

我有以下代碼,我試圖設置ApplicationRoute的模型,但它似乎不工作。我對Ember代碼有一些疑問。首先,我可以爲應用程序路線設置一個模型嗎?其次,如果路由的模型具有名爲count和fileName的字段,那麼是否需要在控制器中聲明這些字段?看起來如果我這樣做,控制器中的值優先於模型值。即使未在任何地方定義總數,我也可以在setupController中執行類似this.set('total',5)的操作。ember.js中的應用程序路由模型

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

你可以這樣做:

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

所以隨時model.count變化,屬性格式會得到自動更新。

而且,您可以直接在路線上設置模型。在控制器中執行this.set('total', 5)時,只能在控制器上設置該屬性,而不是模型。爲了更新模型,你需要做的:

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

最後,您setupController代碼是不正確的。這裏是灰燼文檔(located here)發現樣品方法:

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

那麼你的建議是,我應該在模型中使用計算屬性,這就是一切?實際上,我發現如果只是從ObjectController而不是Controller擴展我的控制器,那麼模型中的屬性在控制器中自動可用 –