2013-11-21 34 views
5

如何在不首先進入路徑的情況下獲取模型加載?emberjs使用「需求」,但其他控制器型號爲空

App.UsersRoute = Em.Route.extend({ 
    model: function() { 
     return ['bob', 'sue', 'tom']; 
    }, 

    setupController: function(controller, model) { 
    controller.set('model', model); 
    } 
}); 

從使用

needs: "users" 

this.get('controllers.users.content'); 

另一個控制器,只要我第一次訪問UsersRoute工作正常。

回答

3

加載它在最上面的路線,將需要它,所以:

App.SomeOtherRoute = Em.Route.extend({ 
    setupController: function(controller, model) { 
    controller.set('model', model); 
    this.controllerFor('user').set('model', ['bob', 'sue', 'tom']); 
    } 
}); 

請注意,如果您使用的餘燼數據或公積金或AJAX,該模型將是一個承諾。你不能設置模型中的控制器是一個承諾,所以你會怎麼做:

setupController: function(controller, model) { 
    controller.set('model', model); 
    return this.get('store').findAll('user').then(function(users) { 
     this.controllerFor('users').set('model', users); 
    }); 
    } 

注意,在我使用UsersController,不UserController的第二個,因爲你似乎想用戶的集合不一個用戶。

+1

看起來像我需要的,但它不填充我的選擇視圖,即contentBinding =「controllers.users.content」。但是,如果我去用戶然後回來它填充。我看到了這個請求,我可以看到商店已經填充。 –

2

我打這個同樣的問題,過去的這個週末和我下面的工作:

App.SomeOtherController = Ember.Controller.extend({ 
    needs: ['users'] 
}); 

App.SomeOtherRoute = Ember.Route.extend({ 
    setupController: function(controller, model){ 
     this._super(controller, model); 
     controller.set('controllers.users.model', ['bob', 'sue', 'tom']); 
    } 
}); 

,如果它是一個Ajax調用/燼數據,那麼你需要的東西是這樣的:

App.SomeOtherController = Ember.Controller.extend({ 
    needs: ['users'] 
}); 

App.SomeOtherRoute = Ember.Route.extend({ 
    setupController: function(controller, model){ 
     this._super(controller, model); 
     this.get('store').findAll('user').then(function(users) { 
     controller.set('controllers.users.model', users); 
     }); 
    } 
}); 

然而,一位同事今天在我們的代碼審查中指出,如果我需要這樣做,我可能錯誤地構建了我的路線/資源/模型。換句話說,外部路線不應該依賴於內部路線的模型。所以我現在考慮回去並重構這個,以便用戶模型是外部路由模型的一部分,然後我可以在我的內部路由控制器中使用它。