Meteor:设置帮助以在模板中设置复选框

时间:2015-09-16 14:47:59

标签: javascript checkbox meteor

我正在使用alanning:角色来检查角色:

helper.js

Template.user.helpers({
    var loggedInUser = Meteor.user()
    var admin = (Roles.userIsInRole(loggedInUser, ['admin'])) ? true : false,
        editor = (Roles.userIsInRole(loggedInUser, ['admin'])) ? true : false;
    var roles = { admin: admin, editor: editor };
    return roles;
});

模板

<template name="user">
    <form>
        <input type="checkbox" name="admin"> Admin
        <input type="checkbox" name="editor"> Admin
    </form>
</template>

如果admin或editor为true,如何设置复选框以进行检查? 或者是否有更好的方法来设置复选框?

2 个答案:

答案 0 :(得分:2)

通常,您希望在onRendered回调中初始化模板的状态,如下所示:

Template.user.onRendered(function() {
  var userId = Meteor.userId();
  $('input[name=admin]').prop('checked', Roles.userIsInRole(userId, ['admin']));
  $('input[name=editor]').prop('checked', Roles.userIsInRole(userId, ['editor']));
});

请注意,根据docsuserIsInRole会获取ID(不是对象)。

如果你有多个角色要检查,你可以像这样迭代它们:

Template.user.onRendered(function() {
  var userId = Meteor.userId();
  var roles = ['admin', 'editor'];
  _.each(roles, function(role) {
    $("input[name=" + role + "]").prop('checked', Roles.userIsInRole(userId, [role]));
  });
});

答案 1 :(得分:0)

您可以根据以下用户角色在页面加载时设置它们:

library

如果您需要反复设置复选框的状态,请按以下步骤操作:

HTML

Template.users.rendered = function() {
  var self = this;
  var loggedInUser = Meteor.userId();
  var admin = (Roles.userIsInRole(loggedInUser, ['admin'])),
      editor = (Roles.userIsInRole(loggedInUser, ['editor']));
  //set the checkboxes correct values
  $(self.find("#admin")).prop('checked', admin);
  $(self.find("#editor")).prop('checked', editor);
};

JAVASCRIPT

<template name="user">
    <form>
        <input type="checkbox" name="admin" {{getValueForChecked "admin"}}> Admin
        <input type="checkbox" name="editor" {{getValueForChecked "editor"}}> Editor
    </form>
</template>