Más gestores de eventos

Hubo errores de script en esta página. Mientras los editores del sitio lo solucionan, puedes ver un contenido parcial debajo.

{{ Traducción("inglés", "XUL Tutorial:More Event Handlers", "en") }}

In this section, the event object is examined and additional events are described.

El objeto de evento

Each event handler has a single argument which holds an event object. In the attribute form of event listener, this event is an implied argument to the script code which can be refered to using the name 'event'. In the addEventListener form, the first argument to the listener function will be the event object. The event object has a number of properties which can be examined during an event. The full list can be found in the referencia al objeto en planeta XUL.

We already saw the event's target property in the last section. It holds a reference to the element where the event occured. A similar property currentTarget holds the element that is currently having its event listeners handled. In the example below, currentTarget is always the vbox, whereas target would be the specific element, either the button or checkbox, that was activated. Ejemplo 1: {{ Xultu-sv("ex_advevents_1.xul") }}

<vbox oncommand="alert(event.currentTarget.tagName);">
  <button label="OK"/>
  <checkbox label="Show images"/>
</vbox>

La evento de parada de propagación

Once you handle an event, regardless of where in the propagation the event is, you will likely want to stop the event from being sent to further elements, essentially stopping the capturing or bubbling phases from continuing. Depending on how you attach the event listener to an element, there are different ways of doing this.

Recall that the capturing phase occurs before the bubbling phase, so any capturing listeners will trigger before any bubbling listeners. If a capturing event stops the event propagation, none of the later capturing listeners, nor any of the bubbling listeners will ever receive notification about the events. To stop event propagation, call the event object's stopPropagation method, as in the following example.

Ejemplo 2: {{ Xultu-sv("ex_advevents_2.xul") }}

<hbox id="outerbox">
  <button id="okbutton" label="OK"/>
</hbox>

<script>
function buttonPressed(event){
  alert('Button was pressed!');
}

function boxPressed(event){
  alert('Box was pressed!');
  event.stopPropagation();
}

var button = document.getElementById("okbutton");
button.addEventListener('command',buttonPressed,true);

var outerbox = document.getElementById("outerbox");
outerbox.addEventListener('command',boxPressed,true);
</script>

Here, an event listener has been added to the button and another event listener has been added to the box. The stopPropagation method has been called in the box's listener, so the button's listener never gets called. If this call was removed, both listeners would be called and both alerts would appear.

Prevent Default Action

If no event handlers have been registered for an event, then after completing the capturing and bubbling phases, the element will handle the event in a default way. What will happen depends on the event and the type of element. For example, the 'popupshowing' event is sent to a popup just before it is displayed. The default action is to display the popup. If the default action is prevented, the popup will not be displayed. The default action can be prevented with the event object's preventDefault method, as in the example below.

Ejemplo 3: {{ Xultu-sv("ex_advevents_3.xul") }}

<button label="Tipos" type="menu">
  <menupopup onpopupshowing="event.preventDefault();">
    <menuitem label="Vidrio"/>
    <menuitem label="Plástico"/>
  </menupopup>
</button>

Alternatively, for attribute event listeners, you can just return false from the code. Note that preventing the default action is not the same as stopping event propagation with the stopPropagation method. Even if the default action has been prevented, the event will still continue to propagate. Similarly, calling the stopPropagation method won't prevent the default action. You must call both methods to stop both from occuring.

Note that once propagation or the default action has been prevented, neither may be re-enabled again for that event.

The following sections list some of the events that may be used. A full list is provided in the referencia al gestor de evento en planeta XUL.

Eventos del ratón

There are several events which can be used to handle mouse specific actions, which are described briefly below:

click
Called when the mouse is pressed and released on an element.
dblclick
Called when the a mouse button is double clicked.
mousedown
Called when a mouse button is pressed down on an element. The event handler will be called as soon as a mouse button is pressed, even if it hasn't been released yet.
mouseup
Called when a mouse button is released on an element.
mouseover
Called when the mouse pointer is moved onto an element. You could use this to highlight the element, however CSS provides a way to do this automatically so you shouldn't do it with an event. You might, however, want to display some help text on a status bar.
mousemove
Called when the mouse pointer is moved while over an element. The event may be called many times as the user moves the mouse so you should avoid performing lengthy tasks frorm this handler.
mouseout
Called when the mouse pointer is moved off of an element. You might then unhighlight the element or remove status text.

There are also a set of drag related events, which occur when the user holds down a mouse button and drags the mouse around. Those events are described in Drag and Drop.

Propiedades del botón del ratón

When a mouse button event occurs, a number of additional properties are available to determine which mouse buttons were pressed and the location of the mouse pointer. The event's button property can be used to determine which button was pressed, where possible values are 0 for the left button, 1 for the right button and 2 for the middle button. If you've configured your mouse differently, these values may be different.

The detail property holds the number of times the button has been clicked quickly in sequence. This allows you to check for single, double or triple clicks. Of course, if you just want to check for double clicks, you can also use the dblclick event instead. The click event will be fired once for the first click, again for the second click, and again for the third click, but the dblclick event will only be fired once for a double click.

The button and detail properties only apply to the mouse button related events, not mouse movement events. For the mousemove event, for example, both properties will be set to 0.

Propiedades de la posición del ratón

However, all mouse events will be supplied with properties that hold the coordinates of the mouse position where the event occured. There are two sets of coordinates. The first is the screenX and screenY properties and are relative to the top left corner of the screen. The second set, clientX and clientY, are relative to the top left corner of the document. Here is an example which displays the current mouse coordinates:

Ejemplo 4: {{ Xultu-sv("ex_advevents_4.xul") }}

<script>

function updateMouseCoordinates(event){
  var text = "X:" + event.clientX + " Y:" + event.clientY;
  document.getElementById("xy").value = text;
}
</script>

<label id="xy"/>
<hbox width="400" height="400" onmousemove="updateMouseCoordinates(event);"/>

In this example, the size of the box has been set explicity so the effect is easier to see. The event handler gets the clientX and clientY properties and creates a string from them. This string is then assigned to the value property of the label. Note that the event argument must be passed to the updateMouseCoordinates function. If you move the mouse quickly across the border of the box, you might notice that the coordinates don't generally stop right at 400. This is because the mousemove events occur at intervals depdending on the speed at which the mouse moves and the mouse is usually moved some distance past the border by the time the next event fires. Obviously, it would be much too inefficient to send a mousemove event for every pixel the mouse is moved.

Element Relative Coordinates

You will often want to get the coordinates of an event relative to the element where the element occured rather than the entire window. You can do this by subtracting the element's position from the event position, as in the following code.

var element = event.target;
var elementX = event.clientX - element.boxObject.x;
var elementY = event.clientY - element.boxObject.y;

XUL elements have a box object that can be retrieved using the boxObject property. We'll learn more about the box object in una sección más adelante, but it holds information pertaining to how the element is displayed, including the x and y position of the element. In this example code, these coordinates are subtracted from the event coordinates to get the event position relative to the element.

Load Events

The load event is sent to the document (la etiqueta de la ventana - <code>window</code>) once the XUL file has finished loading and just before the content is displayed. This event is commonly used to initialize fields and perform other tasks that need to be done before the user can use the window. You should use a load event to do these kinds of things as opposed to adding script at the top level outside a function. This is because the XUL elements may not have loaded or fully initialized yet, so some things may not work as expected. To use a load event, place an onload attribute on the window tag. Call code within the load handler which will initialize the interface as necessary.

There is also an unload event which is called once the window has closed, or in a browser context, when the page is switched to another URL. You can use this event to save any changed information, for example.


Next, we'll find out how to add atajos de teclado.

{{ AnteriorSiguiente("Tutorial de XUL:Añadiendo los gestores de eventos", "Tutorial de XUL:Atajos de teclado") }}

{{ languages( { "en": "en/XUL_Tutorial/More_Event_Handlers", "fr": "fr/Tutoriel_XUL/Plus_sur_les_gestionnaires_d\'\u00e9v\u00e8nements", "ja": "ja/XUL_Tutorial/More_Event_Handlers", "pl": "pl/Kurs_XUL/Wi\u0119cej_funkcji_obs\u0142ugi_zdarze\u0144" } ) }}

Etiquetas y colaboradores del documento

Colaboradores de esta página: Mgjbot, Nathymig
Última actualización por: Mgjbot,