From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../api/eventtarget/addeventlistener/index.html | 335 +++++++++++++++++++++ .../web/api/eventtarget/dispatchevent/index.html | 35 +++ files/es/web/api/eventtarget/index.html | 119 ++++++++ .../api/eventtarget/removeeventlistener/index.html | 217 +++++++++++++ 4 files changed, 706 insertions(+) create mode 100644 files/es/web/api/eventtarget/addeventlistener/index.html create mode 100644 files/es/web/api/eventtarget/dispatchevent/index.html create mode 100644 files/es/web/api/eventtarget/index.html create mode 100644 files/es/web/api/eventtarget/removeeventlistener/index.html (limited to 'files/es/web/api/eventtarget') diff --git a/files/es/web/api/eventtarget/addeventlistener/index.html b/files/es/web/api/eventtarget/addeventlistener/index.html new file mode 100644 index 0000000000..d5b3aa4aef --- /dev/null +++ b/files/es/web/api/eventtarget/addeventlistener/index.html @@ -0,0 +1,335 @@ +--- +title: element.addEventListener +slug: Web/API/EventTarget/addEventListener +translation_of: Web/API/EventTarget/addEventListener +--- +

{{apiref("DOM Events")}}

+ +

Resumen

+ +

addEventListener() Registra un evento a un objeto en específico. El Objeto especifico puede ser un simple elemento en un archivo, el mismo  documento , una ventana o un  XMLHttpRequest.

+ +

Para registrar más de un eventListener, puedes llamar addEventListener() para el mismo elemento pero con diferentes tipos de eventos o parámetros de captura.

+ +

Sintaxis

+ +
target.addEventListener(tipo, listener[, useCapture]);
+target.addEventListener(tipo, listener[, useCapture, wantsUntrusted {{ Non-standard_inline() }}]); // Gecko/Mozilla only
+ +
+
tipo
+
Una cadena representando el  tipo de evento a escuchar.
+
listener
+
El objeto que recibe una notificación cuando un evento de el tipo especificado ocurre. Debe ser un objeto implementando la interfaz EventListener o solo una function en JavaScript.
+
useCapture {{ optional_inline() }}
+
Si es true, useCapture indica que el usuario desea iniciar la captura.   Después de iniciar la captura, todos los eventos del tipo especificado serán lanzados al listener registrado antes de comenzar  a ser controlados por algún EventTarget que esté por debajo en el arbol DOM del documento. +
Note: For event listeners attached to the event target; the event is in the target phase, rather than capturing and bubbling phases. Events in the target phase will trigger all listeners on an element regardless of the useCapture parameter.
+ +
Note: useCapture became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6. You should provide that parameter for broadest compatibility.
+
+
+ +
+
wantsUntrusted {{Non-standard_inline}}
+
If true, the listener receives synthetic events dispatched by web content (the default is false for chrome and true for regular web pages). This parameter is only available in Gecko and is mainly useful for the code in add-ons and the browser itself. See Interaction between privileged and non-privileged pages for an example.
+
+ +

Ejemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>DOM Event Example</title>
+
+<style>
+#t { border: 1px solid red }
+#t1 { background-color: pink; }
+</style>
+
+<script>
+// Function to change the content of t2
+function modifyText() {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = "three";
+}
+
+// Function to add event listener to t
+function load() {
+  var el = document.getElementById("t");
+  el.addEventListener("click", modifyText, false);
+}
+
+document.addEventListener("DOMContentLoaded", load, false);
+</script>
+
+</head>
+<body>
+
+<table id="t">
+   <tr><td id="t1">one</td></tr>
+   <tr><td id="t2">two</td></tr>
+</table>
+
+</body>
+</html>
+
+ +

Ver en el JSFiddle

+ +

En el ejemplo anterior , modifyText() es una listener para los eventos click registrados utilzando addEventListener(). Un click en cualquier parte de la tabla notificara al handler y ejecutara la función  modifyText().

+ +

Si quieres pasar parámetros a la función del listener, debes utilizar funciones anónimas.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>DOM Event Example</title>
+
+<style>
+#t { border: 1px solid red }
+#t1 { background-color: pink; }
+</style>
+
+<script>
+
+// Function to change the content of t2
+function modifyText(new_text) {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = new_text;
+}
+
+// Function to add event listener to t
+function load() {
+  var el = document.getElementById("t");
+  el.addEventListener("click", function(){modifyText("four")}, false);
+}
+</script>
+
+</head>
+<body onload="load();">
+
+<table id="t">
+  <tr><td id="t1">one</td></tr>
+  <tr><td id="t2">two</td></tr>
+</table>
+
+</body>
+</html>
+
+ +

Notas

+ +

¿Porqué utilizar addEventListener?

+ +

addEventListener es la forma de registrar un listener de eventos, como se especifica en W3C DOM. Sus beneficios son los siguientes:

+ + + +

La alternativa,  Antigua forma de registrar event listeners es descrita a continuación.

+ +

Adding a listener during event dispatch

+ +

If an EventListener is added to an EventTarget while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.

+ +

Multiple identical event listeners

+ +

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.

+ +

The value of this within the handler

+ +

It is often desirable to reference the element from which the event handler was fired, such as when using a generic handler for a series of similar elements. When attaching a function using addEventListener() the value of this is changed—note that the value of this is passed to a function from the caller.

+ +

In the example above, the value of this within modifyText() when called from the click event is a reference to the table 't'. This is in contrast to the behavior that occurs if the handler is added in the HTML source:

+ +
<table id="t" onclick="modifyText();">
+  . . .
+
+ +

The value of this within modifyText() when called from the onclick event will be a reference to the global (window) object.

+ +
Note: JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can later remove it.
+ +

This is an example with and without bind:

+ +
var Something = function(element)
+{
+  this.name = 'Something Good';
+  this.onclick1 = function(event) {
+    console.log(this.name); // undefined, as this is the element
+  };
+  this.onclick2 = function(event) {
+    console.log(this.name); // 'Something Good', as this is the binded Something object
+  };
+  element.addEventListener('click', this.onclick1, false);
+  element.addEventListener('click', this.onclick2.bind(this), false); // Trick
+}
+
+ +

A problem in the example above is that you cannot remove the listener with bind. Another solution is using a special function called handleEvent to catch any events:

+ +
var Something = function(element)
+{
+  this.name = 'Something Good';
+  this.handleEvent = function(event) {
+    console.log(this.name); // 'Something Good', as this is the Something object
+    switch(event.type) {
+      case 'click':
+        // some code here...
+        break;
+      case 'dblclick':
+        // some code here...
+        break;
+    }
+  };
+
+  // Note that the listeners in this case are this, not this.handleEvent
+  element.addEventListener('click', this, false);
+  element.addEventListener('dblclick', this, false);
+
+  // You can properly remove the listners
+  element.removeEventListener('click', this, false);
+  element.removeEventListener('dblclick', this, false);
+}
+
+ +

Legacy Internet Explorer and attachEvent

+ +

In Internet Explorer versions prior to IE 9, you have to use attachEvent rather than the standard addEventListener. To support IE, the example above can be modified to:

+ +
if (el.addEventListener) {
+  el.addEventListener('click', modifyText, false);
+} else if (el.attachEvent)  {
+  el.attachEvent('onclick', modifyText);
+}
+
+ +

There is a drawback to attachEvent, the value of this will be a reference to the window object instead of the element on which it was fired.

+ +

Older way to register event listeners

+ +

addEventListener() was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:

+ +
// Pass a function reference — do not add '()' after it, which would call the function!
+el.onclick = modifyText;
+
+// Using a function expression
+element.onclick = function() {
+    // ... function logic ...
+};
+
+ +

This method replaces the existing click event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as blur (onblur), keypress (onkeypress), and so on.

+ +

Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

+ +

Memory issues

+ +
var i;
+var els = document.getElementsByTagName('*');
+
+// Case 1
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", function(e){/*do something*/}, false});
+}
+
+// Case 2
+function processEvent(e){
+  /*do something*/
+}
+
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", processEvent, false});
+}
+
+
+ +

In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to call element.removeEventListener because we do not have a reference to the handler, while in the second case, it's possible to do myElement.removeEventListener("click", processEvent, false).

+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop(1.0) }}9.071.0
useCapture made optional1.06.09.011.60{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{ CompatGeckoMobile(1.0) }}9.06.01.0
+
+ +

Gecko notes

+ + + +

WebKit notes

+ + + +

See Also

+ + + +

Specification

+ + diff --git a/files/es/web/api/eventtarget/dispatchevent/index.html b/files/es/web/api/eventtarget/dispatchevent/index.html new file mode 100644 index 0000000000..22a15ca8b5 --- /dev/null +++ b/files/es/web/api/eventtarget/dispatchevent/index.html @@ -0,0 +1,35 @@ +--- +title: element.dispatchEvent +slug: Web/API/EventTarget/dispatchEvent +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/EventTarget/dispatchEvent +--- +

{{ ApiRef("DOM Events")}}

+ +

Resumen

+ +

Lanza un evento en el sistema de eventos. El evento está sujeto al mismo comportamiento y capacidades que si fuera un evento de lanzamiento directo.

+ +

Sintaxis

+ +
bool = element.dispatchEvent(event)
+
+ + + +

Notas

+ +

Como se ve en el ejemplo anterior, dispatchEvent es el último paso en el proceso crear-inicializar-lanzar, que se usa para el lanzamiento manual de eventos en el modelo de implementación de eventos.

+ +

El evento puede ser creado mediante el método document.createEvent e inicializado usando initEvent u otro método, más específicamente, métodos de inicialización como initMouseEvent o initUIEvent.

+ +

Ver también Event object reference.

+ +

Especificación

+ +

DOM Level 2 Events: dispatchEvent

diff --git a/files/es/web/api/eventtarget/index.html b/files/es/web/api/eventtarget/index.html new file mode 100644 index 0000000000..f263590861 --- /dev/null +++ b/files/es/web/api/eventtarget/index.html @@ -0,0 +1,119 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API +translation_of: Web/API/EventTarget +--- +

{{ ApiRef("DOM Events") }}

+ +

EventTarget es una interfaz implementada por los objetos que pueden administrar eventos y sus escuchadores.

+ +

{{domxref("Element")}}, {{domxref("document")}}, y {{domxref("window")}} son los objetivos más comunes de un evento, pero otros objetos pueden serlo también, por ejemplo {{domxref("XMLHttpRequest")}}, {{domxref("AudioNode")}}, {{domxref("AudioContext")}}, entre otros.

+ +

Muchos objetivos de eventos tales como: elementos, documentos y ventanas, también admiten la configuración de controladores de eventos a través de propiedades y atributos.

+ +

Métodos

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Registre un controlador de eventos de un tipo de evento específico en EventTarget.
+
{{domxref("EventTarget.removeEventListener()")}}
+
Elimina un detector de eventos del EventTarget.
+
{{domxref("EventTarget.dispatchEvent()")}}
+
Enviar un evento a este EventTarget.
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}{{Spec2('DOM3 Events')}}A few parameters are now optional (listener), or accepts the null value (useCapture).
{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Compatibilidad

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("1") }}9.071.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{ CompatGeckoMobile("1") }}9.06.01.0
+
+ +

Additional methods for Mozilla chrome code

+ +

Mozilla extensions for use by JS-implemented event targets to implement on* properties. See also WebIDL bindings.

+ + + +

Vea también

+ + diff --git a/files/es/web/api/eventtarget/removeeventlistener/index.html b/files/es/web/api/eventtarget/removeeventlistener/index.html new file mode 100644 index 0000000000..1b022bbe50 --- /dev/null +++ b/files/es/web/api/eventtarget/removeeventlistener/index.html @@ -0,0 +1,217 @@ +--- +title: EventTarget.removeEventListener() +slug: Web/API/EventTarget/removeEventListener +tags: + - API + - DOM + - Event +translation_of: Web/API/EventTarget/removeEventListener +--- +

{{APIRef("DOM Events")}}

+ +

El método EventTarget.removeEventListener() remueve del {{domxref("EventTarget")}} un detector de evento previamente registrado con {{domxref("EventTarget.addEventListener")}}. El detector de evento a ser removido es identificado usando una combinación de de tipos de eventos, la misma funcion del detector de eventos, y muchas opciones adicionales que pueden afectar

+ +

Sintaxis

+ +
target.removeEventListener(type, listener[, options]);
+target.removeEventListener(tipo, listener[, useCapture])
+ +

Parámetros

+ +
+
tipo
+
Un string representando el tipo de evento del que se está removiendo un detector de evento.
+
detector (listener)
+
La función {{domxref("EventListener")}} del manejador de evento a eliminar del objetivo del evento.
+
options {{optional_inline}}
+
Un objeto que especifíca diversas características acerca del detector de eventos. Las opciones disponibles son: +
    +
  • capture: Un {{jsxref("Boolean")}} que indica que eventos de este tipo serán enviados al listener antes de ser enviado a cualquier EventTarget debado de éste en el DOM.
  • +
  • {{non-standard_inline}} mozSystemGroup: Sólo disponible ejecutando XBL o Firefox' chrome, es un {{jsxref("Boolean")}} que define si el detector es añadido al grupo del sistema.
  • +
+
+
useCapture {{optional_inline}}
+
Especifíca si el {{domxref("EventListener")}} que se está eliminando fue registrado como un detector de captura o no. Si no se indica, por defecto useCapture asumirá el valor false.
+
Si un detector se registro dos veces, uno con captura y otro sin, cada uno debe ser eliminado por separado. La eliminación de un detector de captura no afecta a una versión de "no-captura" del mismo detector, y viceversa.
+
+ +

Valor de retorno

+ +

undefined.

+ +

Coincidiendo disparadores de evento para su eliminación

+ +

Habiendose añadido detector de evento llamando {{domxref("EventTarget.addEventListener", "addEventListener()")}}, puede llegar un punto donde se requiera eliminar. Obviamente, se necesita especificar los mismos parámetros de tipo y listener a removeEventListener(), pero que hay acerca de los parámetros de options o de useCapture?

+ +

Mientras addEventListener() permite añadir el mismo detector más de una vez para el mismo tipo, si la opción es diferente, la única opción que removeEventListener() revisará es la bandera de capture/useCapture. Su valor debe coincidir con removeEventListener() para coincidir, pero otros valores no necesitan corresponder.

+ +

Por ejemplo, considerar la siguiente llamada a addEventListener():

+ +
element.addEventListener("mousedown", handleMouseDown, true);
+ +

Ahora, considera  removeEventListener():

+ +
element.removeEventListener("mousedown", handleMouseDown, false);     // Fallo
+element.removeEventListener("mousedown", handleMouseDown, true);      // Éxito
+ +

La primera llamada falla porque el valor de useCapture no coincide. El segundo valor funciona, puesto que useCapture es igual a su valor cuando se añadió el detector.

+ +

Ahora considera lo siguiente:

+ +
element.addEventListener("mousedown", handleMouseDown, { passive: true });
+ +

Aqui, especificamos un objeto options en el cual passive esta definido como true, mientras que otras opciones son dejados con su valor por defecto de false.

+ +

Vea consecutivamente, cada una de las siguientes llamadas a  removeEventListener(). Cualquiera de éstas donde capture o useCapture es true falla; en todas las demás funciona. Solo la configuración capture importa a removeEventListener().

+ +
element.removeEventListener("mousedown", handleMouseDown, { passive: true });     // Funciona
+element.removeEventListener("mousedown", handleMouseDown, { capture: false });    // Funciona
+element.removeEventListener("mousedown", handleMouseDown, { capture: true });     // Falla
+element.removeEventListener("mousedown", handleMouseDown, { passive: false });    // Funciona
+element.removeEventListener("mousedown", handleMouseDown, false);                 // Funciona
+element.removeEventListener("mousedown", handleMouseDown, true);                  // Falla
+ +

Vale la pena mencionar que algunos navegadores tienen un comportamiento inconsistente, y a menos que se tengan razones específicas, es probablemente una buena idea usar los mismos valores usados por la llamada a addEventListener() al momento de utilizar removeEventListener().

+ +

Notas

+ +

Si un {{ domxref("EventListener") }} es removido de un {{ domxref("EventTarget") }} cuando aún se está procesando el evento, no será ejecutado. Después de ser removido, un {{ domxref("EventListener") }} no será invocado por el evento al cual se registró, sin embargo se podrá adjuntar de nuevo a dicho evento.

+ +

Llamar {{ domxref("removeEventListener") }}  en algún {{ domxref("EventTarget") }} que no contenga el {{ domxref("EventListener") }} especificado será un acción sin efecto, es decir, se podrá llamar {{ domxref("removeEventListener") }} sin efectos negativos en los scripts.

+ +

Ejemplo

+ +

Este es un ejemplo en donde se agrega y después se elimina un {{ domxref("EventListener") }} 

+ +
var body = document.querySelector('body'),
+    clickTarget = document.getElementById('click-target'),
+    mouseOverTarget = document.getElementById('mouse-over-target'),
+    toggle = false;
+
+function makeBackgroundYellow() {
+    'use strict';
+
+    if (toggle) {
+        body.style.backgroundColor = 'white';
+    } else {
+        body.style.backgroundColor = 'yellow';
+    }
+
+    toggle = !toggle;
+}
+
+clickTarget.addEventListener('click',
+    makeBackgroundYellow,
+    false
+);
+
+mouseOverTarget.addEventListener('mouseover', function () {
+    'use strict';
+
+    clickTarget.removeEventListener('click',
+        makeBackgroundYellow,
+        false
+    );
+});
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM WHATWG", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-EventTarget-removeEventListener", "EventTarget.removeEventListener()")}}{{Spec2("DOM2 Events")}}Definición inicial
+ +

Compatibilidad de los navegadores

+ + + +

{{Compat("api.EventTarget.removeEventListener", 3)}}

+ + + +

Polyfill to support older browsers

+ +

addEventListener() and removeEventListener() are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of addEventListener() and removeEventListener() in implementations which do not natively support it. However, this method will not work on Internet Explorer 7 or earlier, since extending the Element.prototype was not supported until Internet Explorer 8.

+ +
if (!Element.prototype.addEventListener) {
+  var oListeners = {};
+  function runListeners(oEvent) {
+    if (!oEvent) { oEvent = window.event; }
+    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) {
+        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }
+        break;
+      }
+    }
+  }
+  Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (oListeners.hasOwnProperty(sEventType)) {
+      var oEvtListeners = oListeners[sEventType];
+      for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+        if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+      }
+      if (nElIdx === -1) {
+        oEvtListeners.aEls.push(this);
+        oEvtListeners.aEvts.push([fListener]);
+        this["on" + sEventType] = runListeners;
+      } else {
+        var aElListeners = oEvtListeners.aEvts[nElIdx];
+        if (this["on" + sEventType] !== runListeners) {
+          aElListeners.splice(0);
+          this["on" + sEventType] = runListeners;
+        }
+        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
+          if (aElListeners[iLstId] === fListener) { return; }
+        }
+        aElListeners.push(fListener);
+      }
+    } else {
+      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };
+      this["on" + sEventType] = runListeners;
+    }
+  };
+  Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (!oListeners.hasOwnProperty(sEventType)) { return; }
+    var oEvtListeners = oListeners[sEventType];
+    for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+    }
+    if (nElIdx === -1) { return; }
+    for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
+      if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); }
+    }
+  };
+}
+
+ +

+ +

Ver también

+ + -- cgit v1.2.3-54-g00ecf