Javascript事件绑定持久性 [英] Javascript event binding persistence

查看:60
本文介绍了Javascript事件绑定持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个不断渲染/销毁的HTML元素,那么对HTML的javascript事件绑定是否仍然存在,或者是否需要在创建/销毁周期中绑定/取消绑定事件?

If you have a HTML element that is constantly rendered/destroyed, do the javascript event bindings to the HTML persist, or is it necessary to bind/unbind events as part of the creation/destruction cycle?

我正在使用D3来生成美国各县的地图。另外,我正在生成一个工具提示覆盖,其中包含点击事件上的按钮以进行有效选择。

I'm using D3 to generate a map of the counties in the US. In addition, I'm generating a tooltip overlay that includes buttons upon a click event for a valid selection.

我绑定了HTML的部分Click事件处理程序tooltip元素的模板,然后将javascript事件处理程序绑定到所述HTML

Part of the click event handler where I bind the HTML of the template to the tooltip element and then bind the javascript event handlers to said HTML

thisObj._tooltip.template = template : "<div id = 'tooltip_template'>" + 
            "<div class = 'county_data'></div>" +
            "<img src = '/static/images/delete.png' width = '28' height = '28' class = 'delete_logo' id = 'close_tooltip' />" +
            "<button id = 'add_prospective_market' class = 'tooltip_button'>Prospective Market</button>" +
            "<button id = 'add_market' class = 'tooltip_button'>Market County</button>" +
            "<button id = 'remove_market' class = 'tooltip_button'>Remove Market</button></div>"

thisObj._tooltip.tooltip.html(thisObj._tooltip.template)
  .style("left", (d3.event.pageX + 10) + "px")
  .style("top", (d3.event.pageY - 50) + "px")
  .style("pointer-events" , "auto")
  .style("width", "400px")
  .style("height", "150px");

$(".county_data").text(d.name + ", " + d.properties.StateCode);

addTooltipHandlers();

thisObj._tooltip.tooltip.transition()
 .duration(800)
 .style("opacity", 1);

我通过

var addTooltipHandlers = function(){
  $("#add_market").on("click", function(){
    console.log("Adding new Market")
  });

  $("#add_prospective_market").on("click", function(){
    console.log("Adding new Prospective market")
  });

  $("#remove_market").on("click", function(){
     console.log("Removing this market")
  });

  $("#close_tooltip")
    .on("mouseover", function(){
      $(this).css({"border-color" : "red", "opacity" : 1});
    })
    .on("mouseout", function(){
      $(this).css({"border-color" : "black", "opacity" : 0.5});
    })
    .on("click", function(){
      console.log("Closing tooltip");

      d3.selectAll($("#" + thisObj._tooltip.county))
        .style("fill", thisObj._currentCounty.color);

      thisObj._tooltip.tooltip.transition()
        .duration(500)
        .style("opacity", 0)
        .style("pointer-events", "none");

      thisObj._tooltip.open = false;
      removeTooltipHandlers();
   });
}

由于工具提示仅在屏幕上显示,直到注册了关闭事件,然后它被销毁,一旦事件监听器绑定到一个元素,当该元素被销毁并重新创建时,该绑定是否仍然存在?

Since a tooltip is only visible on the screen until a close event is registered, and then it is destroyed, once an event listener is bound to an element, does that binding persist when that element is destroyed and re-created?

推荐答案

为了使事件处理程序持续存在,您必须使用事件授权在jquery

In order for event handlers to persist you have to use event delegation in jquery

而不是

$(...).on(event, handler)

use

$(...).on(event, selector, handler)

例如

$('body').on('click','a.saveButton', saveHandler)

这样你就可以将事件处理程序附加到body元素而不是实际元素销毁或添加到DOM。所以处理程序将一直工作,直到你关闭它们。

This way you attach event handler to body element instead of actual element you can destroy or add to DOM. So handlers will work untill your turn them off.

对于所有全局事件处理程序,您可以使用事件命名空间,例如:

Even better for all global event handlers you can use event namespaces, like:

$('body').on('click.app','a.saveButton', saveHandler)
$('body').on('click.app','a.addButton', addHandler)

这将允许你 off 所有这些:

$('body').off('.app')

更新:非常简单 jsfiddle 显示事件委托。

UPDATE: very simple jsfiddle to show event delegation.

这篇关于Javascript事件绑定持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆