简体   繁体   中英

Update documents based on multiple dropdown values

I am building an administration panel within a meteor app to be able to manage the users of the app. Currently I am displaying all the users with a dropdown for each user to change their role .

I need to update the changed roles only after I hit some confirmation button at the end.

I have a template that gets rendered with the username and a dropdown with the current role of the user, my template is similar to this:

<div class="ui selection dropdown">
  <input type="hidden" name="role">
  <i class="dropdown icon"></i>
  <div class="default text">{{role}}</div>
  <div class="menu">
    <div class="item" data-value="admin">Admin</div>
    .
    .
    .
    <div class="item" data-value="user">User</div>
  </div>
</div>  

This renders as many as users I have in my database. I need to update all users who have their role changed after clicking a button.

My current approach is to plug the user id to the dropdown:

<div class="ui selection dropdown" id={{_id}}>

Then I have an event handler for the dropdown change and catch the value:

Template.templateName.events({
  "change .ui.selection.dropdown": function(event, template) {
    var id = template.find(".ui.selection.dropdown").id;
    var role = template.find("input[name=role]").value;
    ...
  },

});

Now I am wondering if I should push those id,role pairs in some session key and update the users after clicking save button or there is a better and more effective alternatives for this ?

Instead of saving them in session variable and clearing session variable on template's destroyed callback, you can add an attribute to the changed element indicating that the element has changed. When save button is clicked, you can use attribute selector to get all the elements that were changed by this user. See the code sample below for further reference.

Template.templateName.events({
  "change .ui.selection.dropdown": function(event, template) {
    var target = $(event.target);
    target.attr("data-changed", "data-changed");
  },
  "click #saveButtonId": function(event, template) {
    var changedElements = template.$(".ui.selection.dropdown[data-changed]");
    var changedItems = [];

    for (var i = 0; i < changedElements.length; i++) {
       var changedElement = changedElements[i];
       changedItems.push({ id: changedElement.id, value: changedElement.value });
       // or
       //changedItems.push([changedElement.id, changedElement.value]);

    }
    // here you can call a meteor method like
    // Meteor.call('updateUserRoles', changedItems); //this updateUserRoles will now get only changed items that you can update in your DB.
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM