2016-09-09 1 views
0

ユーザーの属性に基づいてコントローラのプロパティを設定するのに少し問題があります。今は、ユーザーがグループの管理者になることができるシンプルな設定があります。私はそれを作って、ユーザーがグループの管理者であれば、そのグループのグループ/ショーページに行くとそのグループの投稿を作成するフォームがありますが、これは通常のメンバーには表示されません管理者ではないember - ユーザー/モデルの属性に基づいてコントローラのプロパティを設定していますか?

は今の私のコントローラは、次のようになります。

import Ember from 'ember'; 

export default Ember.Controller.extend({ 

    loggedInUser: Ember.inject.service('user'), 

    isAdmin: Ember.computed(function() { 
     var that = this; 

     //getting the current user and the list of groups they are 
     //the admin of 
     this.get('loggedInUser').get('currentUser.administrating') 
      .then(function(groups) { 

       //getting the id of the current group 
       var groupID = that.get('group').get('id'); 

        //looping over each group the user is an admin of 
        //and comparing the id to the current groups id 
        groups.forEach(function(group) { 
         if (group.get('id') == groupID) { 
          that.set('isAdmin', true); 
         } 
        }) 
      }); 
    }) 


}); 

問題は、これが唯一の初めての作品です。たとえば、ユーザーが特定のグループのグループ/ショーページにアクセスし、そのグループの管理者である場合は、そのフォームがきれいに表示されます。ただし、他のグループの他のグループ/ショーページをさらに訪問すると、そのユーザーがそのグループの管理者ではない場合でも、フォームが表示されます。私はいくつかの掘り下げを行ったし、それはコントローラがシングルトンであり、他のページに移動するときに問題が残っているようだ。私はsetupControllerをルートに使用してisAdminをfalseに設定しましたが、毎回そのプロパティをfalseに設定するだけです。これを行う適切な方法はありますか?

+0

A com puted関数は(通常)約束を返すことができません。また、再計算を開始するための依存プロパティも必要です。最後に、何かを返さなければなりません。何も返さないのです。この特定のケースでは、オブザーバを使用することを検討します。オブザーバは、プロパティが変更されるたびに同期して再実行されます。ところで、あなたの 'forEach'はおそらく' includes'を使って書き直すことができます。 –

答えて

0

@torazaburoはコメントに記載されているように、計算されたプロパティには依存キーが必要です。それがなければ、ユーザーが変更したときに再計算されません。

また、あなたのコードのこの部分は

groups.forEach(function(group) { 
    if (group.get('id') == groupID) { 
    that.set('isAdmin', true); 
    } 
}) 

は、あなたがグループ/ショーのページ内にある一方で、ユーザが変更されない場合は、別のアプローチがするだろう。この

groups.forEach(function(group) { 
    if (group.get('id') === groupID) { 
    return true; 
    } 
}); 
return false; 

ようになるはずですsetupControllerからコントローラー関数を呼び出すだけで、このようにisAdminを設定します。

//routes/groups/show.js 
... 
setupController(controller, model) { 
this._super(controller, model); 
controller.setAdmin(); 
... 

//controllers/groups/show.js 
... 
isAdmin: false, 
setAdmin() { 
var that = this; 

    //getting the current user and the list of groups they are 
    //the admin of 
    this.get('loggedInUser').get('currentUser.administrating') 
     .then(function(groups) { 

      //getting the id of the current group 
      var groupID = that.get('group').get('id'); 

       //looping over each group the user is an admin of 
       //and comparing the id to the current groups id 
       groups.forEach(function(group) { 
        if (group.get('id') == groupID) { 
         that.set('isAdmin', true); 
         return; 
        } 
       }); 
       this.set('isAdmin', false); 

     }); 
} 
関連する問題