简体   繁体   English

在动态创建的DOM令牌上的KnockoutJS Click绑定

[英]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. 我想将click事件绑定到每个角色旁边显示的白色十字图标。 A Role is simply an entity (JS object) with a Name property. 角色只是具有Name属性的实体(JS对象)。

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. 即使我的HTML标记上有data-bind="click: removeRoleForSelectedUser(role)" ,它仍然不会触发该事件,因此我猜测它没有绑定。

I went to Google for answers, and saw this . 我去谷歌寻求答案, 看到了 so I tried to do that binding on my role token (targeting the id property). 因此我尝试对我的角色令牌进行绑定(定位id属性)。 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. 也不必重复调用applyBindings ,因此您至少也应该删除该部分。 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. 在没有看到更多有关您的问题的代码的情况下,很难说上述内容是否正确,但这应该可以帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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