diff options
Diffstat (limited to 'files/es/web/api/eventtarget')
-rw-r--r-- | files/es/web/api/eventtarget/addeventlistener/index.html | 335 | ||||
-rw-r--r-- | files/es/web/api/eventtarget/dispatchevent/index.html | 35 | ||||
-rw-r--r-- | files/es/web/api/eventtarget/index.html | 119 | ||||
-rw-r--r-- | files/es/web/api/eventtarget/removeeventlistener/index.html | 217 |
4 files changed, 706 insertions, 0 deletions
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 +--- +<p>{{apiref("DOM Events")}}</p> + +<h2 id="Summary" name="Summary">Resumen</h2> + +<p><code>addEventListener()</code> Registra un evento a un objeto en específico. El <a href="/en-US/docs/DOM/EventTarget" title="DOM/EventTarget">Objeto especifico</a> puede ser un simple <a href="/en-US/docs/DOM/element" title="DOM/element">elemento</a> en un archivo, el mismo <code><a href="/en-US/docs/DOM/document" title="DOM/document">documento</a></code> , una <code><a href="/en-US/docs/DOM/window" title="DOM/window">ventana</a></code> o un <code><a href="/en-US/docs/DOM/XMLHttpRequest" title="XMLHttpRequest">XMLHttpRequest</a></code>.</p> + +<p>Para registrar más de un eventListener, puedes llamar <code>addEventListener()</code> para el mismo elemento pero con diferentes tipos de eventos o parámetros de captura.</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox notranslate"><code><em>target</em>.addEventListener(tipo, <em>listener</em>[, <em>useCapture</em>]); +<em>target</em>.addEventListener(tipo, <em>listener</em>[, <em>useCapture</em>, <em>wantsUntrusted </em>{{ Non-standard_inline() }}]); // Gecko/Mozilla only</code></pre> + +<dl> + <dt><code>tipo</code></dt> + <dd>Una cadena representando el <a class="internal" href="/en-US/docs/DOM/event.type" title="DOM/Event.type">tipo de evento</a> a escuchar.</dd> + <dt><code>listener</code></dt> + <dd>El objeto que recibe una notificación cuando un evento de el tipo especificado ocurre. Debe ser un objeto implementando la interfaz <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener"><code>EventListener</code></a> o solo una <a href="/en-US/docs/JavaScript/Guide/Functions" title="JavaScript/Guide/Functions">function</a> en JavaScript.</dd> + <dt><code>useCapture</code> {{ optional_inline() }}</dt> + <dd>Si es <code>true</code>, <code>useCapture</code> indica que el usuario desea iniciar la captura. Después de iniciar la captura, todos los eventos del tipo especificado serán lanzados al <code>listener</code> registrado antes de comenzar a ser controlados por algún <code>EventTarget</code> que esté por debajo en el arbol DOM del documento. + <div class="note"><strong>Note:</strong> 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 <code>useCapture</code> parameter.</div> + + <div class="note"><strong>Note:</strong> <code>useCapture</code> 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.</div> + </dd> +</dl> + +<dl> + <dt>wantsUntrusted {{Non-standard_inline}}</dt> + <dd>If <code>true</code>, the listener receives synthetic events dispatched by web content (the default is <code>false</code> for chrome and <code>true</code> 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 <a href="https://developer.mozilla.org/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interaction between privileged and non-privileged pages</a> for an example.</dd> +</dl> + +<h2 id="Example" name="Example">Ejemplo</h2> + +<pre class="brush: html notranslate"><!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> +</pre> + +<p><a href="https://jsfiddle.net/madBYK/UumUP">Ver en el JSFiddle</a></p> + +<p>En el ejemplo anterior , <code>modifyText()</code> es una listener para los eventos <code style="font-style: normal; line-height: 1.5;">click</code><span style="line-height: 1.5;"> registrados utilzando</span><span style="line-height: 1.5;"> </span><code style="font-style: normal; line-height: 1.5;">addEventListener()</code><span style="line-height: 1.5;">. Un click en cualquier parte de la tabla notificara al handler y ejecutara la función </span><code style="font-style: normal; line-height: 1.5;">modifyText()</code><span style="line-height: 1.5;">.</span></p> + +<p>Si quieres pasar parámetros a la función del listener, debes utilizar funciones anónimas.</p> + +<pre class="brush: html notranslate"><!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> +</pre> + +<h2 id="Notas">Notas</h2> + +<h3 id="Why_use_addEventListener.3F" name="Why_use_addEventListener.3F">¿Porqué utilizar <code>addEventListener</code>?</h3> + +<p><code>addEventListener</code> es la forma de registrar un listener de eventos, como se especifica en W3C DOM. Sus beneficios son los siguientes:</p> + +<ul> + <li>Permite agregar mas de un listener a un solo evento. Esto es particularmente útil para las librerias <a href="/en-US/docs/DHTML" title="DHTML">DHTML</a> o las <a href="/en-US/docs/Extensions" title="Extensions">Extensiones de Mozilla</a> que deben funcionar bien, incluso si se utilizan otras librerias/extensiones.</li> + <li>Da un control mas detallado de la fase en la que el listener se activa (capturing vs. bubbling)</li> + <li>Funciona en cualquier elemento del DOM, no únicamente con elementos de HTML.</li> +</ul> + +<p>La alternativa, <a href="#Older_way_to_register_event_listeners">Antigua forma de registrar event listeners</a> es descrita a continuación.</p> + +<h3 id="Adding_a_listener_during_event_dispatch" name="Adding_a_listener_during_event_dispatch">Adding a listener during event dispatch</h3> + +<p>If an <code>EventListener</code> is added to an <code>EventTarget</code> 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.</p> + +<h3 id="Multiple_identical_event_listeners" name="Multiple_identical_event_listeners">Multiple identical event listeners</h3> + +<p>If multiple identical <code>EventListener</code>s are registered on the same <code>EventTarget</code> with the same parameters, the duplicate instances are discarded. They do not cause the <code>EventListener</code> to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the <a href="/en-US/docs/Web/API/EventTarget/removeEventListener" title="DOM/element.removeEventListener">removeEventListener</a> method.</p> + +<h3 id="The_value_of_this_within_the_handler" name="The_value_of_this_within_the_handler">The value of <code>this</code> within the handler</h3> + +<p>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 <code>addEventListener()</code> the value of <code>this</code> is changed—note that the value of <code>this</code> is passed to a function from the caller.</p> + +<p>In the example above, the value of <code>this</code> within <code>modifyText()</code> 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:</p> + +<pre class="brush: html notranslate"><table id="t" onclick="modifyText();"> + . . . +</pre> + +<p>The value of <code>this</code> within <code>modifyText()</code> when called from the onclick event will be a reference to the global (window) object.</p> + +<div class="note"><strong>Note:</strong> JavaScript 1.8.5 introduces the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind()</a></code> method, which lets you specify the value that should be used as <code>this</code> 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.</div> + +<p>This is an example with and without <code>bind</code>:</p> + +<pre class="brush: js notranslate">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 +} +</pre> + +<p>A problem in the example above is that you cannot remove the listener with <code>bind</code>. Another solution is using a special function called <code>handleEvent</code> to catch any events:</p> + +<pre class="brush: js notranslate">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); +} +</pre> + +<h3 id="Compatibility" name="Compatibility">Legacy Internet Explorer and attachEvent</h3> + +<p>In Internet Explorer versions prior to IE 9, you have to use <code><a class="external" href="http://msdn.microsoft.com/en-us/library/ms536343(VS.85).aspx">attachEvent</a></code> rather than the standard <code>addEventListener</code>. To support IE, the example above can be modified to:</p> + +<pre class="brush: js notranslate">if (el.addEventListener) { + el.addEventListener('click', modifyText, false); +} else if (el.attachEvent) { + el.attachEvent('onclick', modifyText); +} +</pre> + +<p>There is a drawback to <code>attachEvent</code>, the value of <code>this</code> will be a reference to the <code>window</code> object instead of the element on which it was fired.</p> + +<h3 id="Older_way_to_register_event_listeners" name="Older_way_to_register_event_listeners">Older way to register event listeners</h3> + +<p><code>addEventListener()</code> was introduced with the DOM 2 <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events">Events</a> specification. Before then, event listeners were registered as follows:</p> + +<pre class="brush: js notranslate">// 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 ... +}; +</pre> + +<p>This method replaces the existing <code>click</code> event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as <code>blur</code> (<code>onblur</code>), <code>keypress</code> (<code>onkeypress</code>), and so on.</p> + +<p>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 <code>addEventListener()</code> are needed.</p> + +<h3 id="Memory_issues" name="Memory_issues">Memory issues</h3> + +<pre class="brush: js notranslate">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}); +} + +</pre> + +<p>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 <code><a href="/en-US/docs/Web/API/EventTarget/removeEventListener" title="DOM/element.removeEventListener">element.removeEventListener</a></code> because we do not have a reference to the handler, while in the second case, it's possible to do <code>myElement.removeEventListener("click", processEvent, false)</code>.</p> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Browser compatibility</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop(1.0) }}</td> + <td>9.0</td> + <td>7</td> + <td>1.0</td> + </tr> + <tr> + <td><code>useCapture</code> made optional</td> + <td>1.0</td> + <td>6.0</td> + <td>9.0</td> + <td>11.60</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoMobile(1.0) }}</td> + <td>9.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> + +<h4 id="Gecko_notes">Gecko notes</h4> + +<ul> + <li>Prior to Firefox 6, the browser would throw if the <code>useCapture</code> parameter was not explicitly <code>false</code>. Prior to Gecko 9.0 {{ geckoRelease("9.0") }}, <code>addEventListener()</code> would throw an exception if the <code>listener</code> parameter was <code>null</code>; now the method returns without error, but without doing anything.</li> +</ul> + +<h4 id="WebKit_notes">WebKit notes</h4> + +<ul> + <li>Although WebKit has explicitly added <code>[optional]</code> to the <code>useCapture</code> parameter <a class="external" href="http://trac.webkit.org/changeset/89781">as recently as June 2011</a>, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.</li> +</ul> + +<h2 id="Specification" name="Specification">See Also</h2> + +<ul> + <li><a href="/en-US/docs/DOM/element.removeEventListener" title="DOM/element.removeEventListener">element.removeEventListener()</a></li> + <li><a href="/en-US/docs/DOM/Creating_and_triggering_events" title="DOM/Creating_and_triggering_custom_events">Creating and triggering custom events</a></li> + <li><a class="external" href="http://www.quirksmode.org/js/this.html" title="http://www.quirksmode.org/js/this.html">More details on the use of <code>this</code> in event handlers</a></li> +</ul> + +<h2 id="Specification" name="Specification">Specification</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener" title="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener">DOM Level 2 Events: EventTarget.addEventListener</a></li> + <li><a class="external" href="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#events-EventTarget-addEventListener" title="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#events-EventTarget-addEventListener">DOM Level 3 Events: EventTarget.addEventListener</a></li> +</ul> 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 +--- +<p>{{ ApiRef("DOM Events")}}</p> + +<h3 id="Resumen" name="Resumen">Resumen</h3> + +<p>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.</p> + +<h3 id="Sintaxis" name="Sintaxis">Sintaxis</h3> + +<pre class="eval"><em>bool</em> = <em>element</em>.dispatchEvent(<em>event</em>) +</pre> + +<ul> + <li><code>element</code> es el objetivo (<code>target</code> en Inglés) del evento.</li> + <li><code>event</code> es un objeto de tipo <a href="es/DOM/event">event</a> que será lanzado.</li> + <li>El valor devuelto es <code>false</code>, si al menos uno de los negociadores (en Inglés:<em>handler</em> ) que manejan el evento es <a href="es/DOM/event.preventDefault">preventDefault</a>. En caso contrario, devuelve <code>true</code>.</li> +</ul> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Como se ve en el ejemplo anterior, <code>dispatchEvent</code> 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.</p> + +<p>El evento puede ser creado mediante el método <a href="es/DOM/document.createEvent">document.createEvent</a> e inicializado usando <a href="es/DOM/event.initEvent">initEvent</a> u otro método, más específicamente, métodos de inicialización como <a href="es/DOM/event.initMouseEvent">initMouseEvent</a> o <a href="es/DOM/event.initUIEvent">initUIEvent</a>.</p> + +<p>Ver también <a href="es/DOM/event">Event object reference</a>.</p> + +<h3 id="Especificaci.C3.B3n" name="Especificaci.C3.B3n">Especificación</h3> + +<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-dispatchEvent">DOM Level 2 Events: dispatchEvent</a></p> 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 +--- +<p>{{ ApiRef("DOM Events") }}</p> + +<p><code>EventTarget</code> es una interfaz implementada por los objetos que pueden administrar eventos y sus escuchadores.</p> + +<p>{{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.</p> + +<p>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.</p> + +<h2 id="Methods" name="Methods">Métodos</h2> + +<dl> + <dt>{{domxref("EventTarget.addEventListener()")}}</dt> + <dd>Registre un controlador de eventos de un tipo de evento específico en EventTarget.</dd> + <dt>{{domxref("EventTarget.removeEventListener()")}}</dt> + <dd>Elimina un detector de eventos del EventTarget.</dd> + <dt>{{domxref("EventTarget.dispatchEvent()")}}</dt> + <dd>Enviar un evento a este EventTarget.</dd> +</dl> + +<h2 id="Specification" name="Specification">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>No change.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}</td> + <td>{{Spec2('DOM3 Events')}}</td> + <td>A few parameters are now optional (<code>listener</code>), or accepts the <code>null</code> value (<code>useCapture</code>).</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}</td> + <td>{{Spec2('DOM2 Events')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoDesktop("1") }}</td> + <td>9.0</td> + <td>7</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{ CompatGeckoMobile("1") }}</td> + <td>9.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Additional_methods_for_Mozilla_chrome_code">Additional methods for Mozilla chrome code</h3> + +<p>Mozilla extensions for use by JS-implemented event targets to implement on* properties. See also <a href="/en-US/docs/Mozilla/WebIDL_bindings" title="/en-US/docs/Mozilla/WebIDL_bindings">WebIDL bindings</a>.</p> + +<ul> + <li>void <strong>setEventHandler</strong>(DOMString type, EventHandler handler) {{ non-standard_inline() }}</li> + <li>EventHandler <strong>getEventHandler</strong>(DOMString type) {{ non-standard_inline() }}</li> +</ul> + +<h2 id="Vea_también">Vea también</h2> + +<ul> + <li><a href="/en-US/docs/Web/Reference/Events" title="/en-US/docs/Web/Reference/Events">Event reference</a> - Los eventos disponibles en la plataforma</li> + <li><a href="/en-US/docs/Web/Guide/DOM/Events" title="/en-US/docs/Web/Guide/DOM/Events">Event developer guide</a> - Guía sobre eventos para desarrolladores</li> + <li>{{domxref("Event")}} - Interface</li> +</ul> 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 +--- +<p>{{APIRef("DOM Events")}}</p> + +<p>El método <strong><code>EventTarget.removeEventListener()</code></strong> 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</p> + +<h2 id="Syntax" name="Syntax">Sintaxis</h2> + +<pre class="syntaxbox"><var>target</var>.removeEventListener(<var>type</var>, <var>listener</var>[, <var>options</var>]); +<em>target</em>.removeEventListener(<em>tipo</em>, <em>listener</em>[, <em>useCapture</em>])</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><var>tipo</var></dt> + <dd>Un string representando el tipo de evento del que se está removiendo un detector de evento.</dd> + <dt><var>detector (listener)</var></dt> + <dd>La función {{domxref("EventListener")}} del manejador de evento a eliminar del objetivo del evento.</dd> + <dt><var>options</var> {{optional_inline}}</dt> + <dd>Un objeto que especifíca diversas características acerca del detector de eventos. Las opciones disponibles son: + <ul> + <li><code>capture</code>: Un {{jsxref("Boolean")}} que indica que eventos de este tipo serán enviados al <code>listener</code> antes de ser enviado a cualquier <code>EventTarget</code> debado de éste en el DOM.</li> + <li>{{non-standard_inline}}<code> mozSystemGroup</code>: Sólo disponible ejecutando XBL o Firefox' chrome, es un {{jsxref("Boolean")}} que define si el detector es añadido al grupo del sistema.</li> + </ul> + </dd> + <dt><code>useCapture</code> {{optional_inline}}</dt> + <dd>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 <code>useCapture</code> asumirá el valor <code>false</code>.</dd> + <dd>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.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p><code>undefined</code>.</p> + +<h3 id="Coincidiendo_disparadores_de_evento_para_su_eliminación">Coincidiendo disparadores de evento para su eliminación</h3> + +<p>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 <code>tipo</code> y <code>listener</code> a <code>removeEventListener()</code>, pero que hay acerca de los parámetros de <code>options</code> o de <code>useCapture</code>?</p> + +<p>Mientras <code>addEventListener()</code> 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 <code>removeEventListener()</code> revisará es la bandera de <code>capture</code>/<code>useCapture</code>. Su valor debe coincidir con <code>removeEventListener()</code> para coincidir, pero otros valores no necesitan corresponder.</p> + +<p>Por ejemplo, considerar la siguiente llamada a <code>addEventListener()</code>:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">true</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>Ahora, considera <code>removeEventListener()</code>:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">false</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Fallo</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">true</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Éxito</span></code></pre> + +<p>La primera llamada falla porque el valor de <code>useCapture</code> no coincide. El segundo valor funciona, puesto que <code>useCapture</code> es igual a su valor cuando se añadió el detector.</p> + +<p>Ahora considera lo siguiente:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> passive<span class="punctuation token">:</span> <span class="boolean token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>Aqui, especificamos un objeto <code>options</code> en el cual <code>passive</code> esta definido como <code>true</code>, mientras que otras opciones son dejados con su valor por defecto de <code>false</code>.</p> + +<p>Vea consecutivamente, cada una de las siguientes llamadas a <code>removeEventListener()</code>. Cualquiera de éstas donde <code>capture</code> o <code>useCapture</code> es <code>true</code> falla; en todas las demás funciona. Solo la configuración <code>capture</code> importa a <code>removeEventListener()</code>.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> passive<span class="punctuation token">:</span> <span class="boolean token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> capture<span class="punctuation token">:</span> <span class="boolean token">false</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> capture<span class="punctuation token">:</span> <span class="boolean token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Falla</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="punctuation token">{</span> passive<span class="punctuation token">:</span> <span class="boolean token">false</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">false</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Funciona</span> +element<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">"mousedown"</span><span class="punctuation token">,</span> handleMouseDown<span class="punctuation token">,</span> <span class="boolean token">true</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Falla</span></code></pre> + +<p>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 <code>addEventListener()</code> al momento de utilizar <code>removeEventListener()</code>.</p> + +<h2 id="Notas">Notas</h2> + +<p>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.</p> + +<p>Llamar {{ domxref("<code>removeEventListener</code>") }} en algún {{ domxref("EventTarget") }} que no contenga el {{ domxref("EventListener") }} especificado será un acción sin efecto, es decir, se podrá llamar {{ domxref("<code>removeEventListener</code>") }} sin efectos negativos en los scripts.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Este es un ejemplo en donde se agrega y después se elimina un {{ domxref("EventListener") }} </p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> body <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">querySelector</span><span class="punctuation token">(</span><span class="string token">'body'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + clickTarget <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">getElementById</span><span class="punctuation token">(</span><span class="string token">'click-target'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + mouseOverTarget <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">getElementById</span><span class="punctuation token">(</span><span class="string token">'mouse-over-target'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + toggle <span class="operator token">=</span> <span class="boolean token">false</span><span class="punctuation token">;</span> + +<span class="keyword token">function</span> <span class="function token">makeBackgroundYellow</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="string token">'use strict'</span><span class="punctuation token">;</span> + + <span class="keyword token">if</span> <span class="punctuation token">(</span>toggle<span class="punctuation token">)</span> <span class="punctuation token">{</span> + body<span class="punctuation token">.</span>style<span class="punctuation token">.</span>backgroundColor <span class="operator token">=</span> <span class="string token">'white'</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="punctuation token">{</span> + body<span class="punctuation token">.</span>style<span class="punctuation token">.</span>backgroundColor <span class="operator token">=</span> <span class="string token">'yellow'</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + + toggle <span class="operator token">=</span> <span class="operator token">!</span>toggle<span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +clickTarget<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'click'</span><span class="punctuation token">,</span> + makeBackgroundYellow<span class="punctuation token">,</span> + <span class="boolean token">false</span> +<span class="punctuation token">)</span><span class="punctuation token">;</span> + +mouseOverTarget<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'mouseover'</span><span class="punctuation token">,</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="string token">'use strict'</span><span class="punctuation token">;</span> + + clickTarget<span class="punctuation token">.</span><span class="function token">removeEventListener</span><span class="punctuation token">(</span><span class="string token">'click'</span><span class="punctuation token">,</span> + makeBackgroundYellow<span class="punctuation token">,</span> + <span class="boolean token">false</span> + <span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th>Especificación</th> + <th>Estado</th> + <th>Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM2 Events", "#Events-EventTarget-removeEventListener", "EventTarget.removeEventListener()")}}</td> + <td>{{Spec2("DOM2 Events")}}</td> + <td>Definición inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidad de los navegadores</h2> + + + +<p>{{Compat("api.EventTarget.removeEventListener", 3)}}</p> + +<ul> +</ul> + +<h2 id="Polyfill_to_support_older_browsers">Polyfill to support older browsers</h2> + +<p><code>addEventListener()</code> and <code>removeEventListener()</code> 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 <code>addEventListener()</code> and <code>removeEventListener()</code> 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.</p> + +<pre class="brush: js">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); } + } + }; +} +</pre> + +<h3 id="Example" name="Example"></h3> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{ domxref("EventTarget.addEventListener()") }}.</li> + <li>{{non-standard_inline}}{{domxref("EventTarget.detachEvent()")}}.</li> +</ul> |