简体   繁体   中英

KnockoutJS Click binding on a dynamically created DOM token

By "token", I mean one of these things:

用户授权小部件

I'd like to bind a click event to the white cross icon that appears next to each Role. A Role is simply an entity (JS object) with a Name property.

To get from a Role, to a token, I have the following function:

var closeIcon = '&nbsp;<i class="fa fa-times-circle" aria-hidden="true" data-bind="click: removeRoleForSelectedUser(role)" id="remove-role-btn"></i>';
self.createRoleToken = function(roleName) {
  return roleName + ' ' + closeIcon;
};

The looping is happening here:

<div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
  <div class="role-token" data-bind="html: $root.createRoleToken(name())"></div>
</div>

Even though I have the data-bind="click: removeRoleForSelectedUser(role)" on my HTML markup, it still doesn't trigger the event, so I'm guessing it isn't bound.

I went to Google for answers, and saw this . so I tried to do that binding on my role token (targeting the id property). I did the binding on user selection as seen here:

self.setCurrentUser = function (user) {
  const newRolesArray = self.roles().filter(function (role) {
    return !contains(user.roles(), role);
  });
  self.userAvailableRoles(newRolesArray);
  self.selectedUser(user);
  ko.applyBindings(self, document.getElementById("remove-role-btn"));
}

That didn't work. It threw the following error:

chrome控制台错误

What am I missing?

Rather than having a complex function that returns markup with extra bindings in, you should instead make the close icon part of the general template:

<div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
  <div class="role-token">
    <span data-bind="text: name"></span>
    <i class="fa fa-times-circle" aria-hidden="true" data-bind="click: $root.removeRoleForSelectedUser"></i>
  </div>
</div>

There should also be no need to repeatedly call applyBindings , so you should also at least remove that part. Without seeing more of the code surrounding your question, it's hard to say if the above is exactly right, but it should get you on the way.

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