简体   繁体   English

如何从更改的模板中删除 Knockoutjs 事件处理程序

[英]How to remove knockoutjs event handler from changed template

I'm looking the way of how to remove event handler from disappeared UI template.我正在寻找如何从消失的 UI 模板中删除事件处理程序的方法。

For example I have an element with template binding.例如,我有一个带有模板绑定的元素。

Template name comes from observable property.模板名称来自可观察的属性。 When I set the valid name, template renders button with click binding / event.当我设置有效名称时,模板呈现带有单击绑定/事件的按钮。 When I pass undefined as the name, template renders nothing.当我将 undefined 作为名称传递时,模板不呈现任何内容。

What happens to event handler and binding?事件处理程序和绑定会发生什么?

UPD: Some code from my head: UPD:脑子里的一些代码:

<div data-bind="template: { name: templateName }"></div>

<script type="text/html" id="btn-tmpl">
    <button data-bind="click: $root.buttonClick">Click me</button>
</script>

<script>
    var vm = {
        templateName: ko.observable('btn-tmpl'),
        buttonClick: function(){ alert('clicked'); }
    };

    ko.applyBindings(vm);
</script>

There are 2 scenarios here这里有2个场景

  1. templateName value starts with undefined. templateName 值以 undefined 开头。
  2. templateName value starts with "btn-tmpl" and is changed to undefined. templateName 值以“btn-tmpl”开头并更改为未定义。

In the first case the template binding will not simply not render anything as there is no name.在第一种情况下,模板绑定不会简单地不呈现任何内容,因为没有名称。 Therefore there is no button element in the DOM and no event因此,DOM 中没有按钮元素,也没有事件

In the second case, when the templateName is cleared KO will empty the contents of the div with the template binding, this includes cleaning up all event handlers.在第二种情况下,当 templateName 被清除时,KO 将清空具有模板绑定的 div 的内容,这包括清理所有事件处理程序。

As a further note, a script element with type "text/html" is not actually passed by the browser as DOM nodes.进一步说明,类型为“text/html”的脚本元素实际上并没有被浏览器作为 DOM 节点传递。 You will not be able to locate that button element in the DOM and so KO will not have wired up an event handler您将无法在 DOM 中找到该按钮元素,因此 KO 将不会连接事件处理程序

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

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