我们在项目中遇到了同样的情况,页面中的所有内容都应该根据授予用户的权限显示和隐藏,这是我想出的解决方案。
您需要先在用户中保存权限并在客户端加载它们;然后您可以按如下方式检查它们
1-在基本视图中声明“filterByPermission”函数(所有视图都应该继承这个)
class SampleProject.Views.BaseView extends Backbone.View
filterByPermission:=>
#these views will be removed incase user does not have a specific permission
if @views_permissions?
for permission, selector of @views_permissions
unless SampleProject.current_user.has_permission permission
@$(selector).remove()
#these views will be removed incase user has a specific permission
if @remove_views_permissions?
for permission, selector of @remove_views_permissions
if SampleProject.current_user.has_permission permission
@$(selector).remove()
2-然后您可以进入另一个继承基本视图的视图并在“views_permissions”中定义您的权限(类似于事件哈希)
class SampleProject.Views.UsersIndex extends SampleProject.Views.BaseView
views_permissions:
"create_users": "#js_create_user_li, #new_user_modal"
"import_users": "#js_import_btn_li, #import_form_li"
"edit_users" : "#edit_user_modal"
"delete_users" : "#js_delete_user_li, .js-user-selector-header"
render:=>
#render your view here
@filterByPermission()
3 渲染视图后调用@filterByPermission()。
这样您就可以在一个地方根据权限控制视图,而无需在整个代码中添加 if 语句