La interfaz IDBCursor
de la IndexedDB API representa un cursor para atravesar o iterar varios registros de una base de datos.
El cursor tiene una fuente que indica el índice o el almacén de objetos sobre el que se está iterando. Tiene una posición dentro del rango y se mueve en una dirección que aumenta o disminuye en el orden de las Keys de registro. El cursor permite a una aplicación procesar asincrónicamente todos los registros del rango del cursor.
Puede tener un número ilimitado de cursores al mismo tiempo. Siempre se obtiene el mismo objeto IDBCursor
que representa un cursor determinado. Las operaciones se realizan en el índice subyacente o en el almacén de objetos.
Methods
IDBCursor.advance()
- Establece el número de veces que un cursor debe mover su posición hacia adelante.
IDBCursor.continue()
- Avanza el cursor a la siguiente posición a lo largo de su dirección, hasta el elemento cuya
key
coincide con el parámetro clave opcional.
IDBCursor.delete()
- Devuelve un objeto
IDBRequest
y, en un hilo separado, elimina el registro en la posición del cursor, sin cambiar la posición del cursor. Esto se puede utilizar para borrar registros específicos. IDBCursor.update()
- Devuelve un objeto
IDBRequest
y, en un hilo separado, actualiza el valor en la posición actual del cursor en el almacén de objetos. Esto se puede utilizar para actualizar registros específicos.
Propiedades
IDBCursor.source
Read only- Devuelve
IDBObjectStore
oIDBIndex
} que el cursor está iterando. Esta función nunca devuelve nulo o lanza una excepción, incluso si el cursor está siendo iterado, ha iterado más allá de su final, o su transacción no está activa. IDBCursor.direction
Read only- Devuelve la dirección de desplazamiento del cursor. Ver Constants para valores posibles.
IDBCursor.key
Read only- Devuelve la
key
del registro en la posición del cursor. Si el cursor está fuera de su rango, se fija enundefined
. Lakey
del cursor puede ser de cualquier tipo de datos. IDBCursor.primaryKey
Read only- Devuelve la
key
primaria efectiva actual del cursor. Si el cursor está siendo iterado o ha iterado fuera de su rango, se fija enundefined
. Lakey
principal del cursor puede ser cualquier tipo de datos.
Constants
Desaprobado Gecko 13 (Firefox 13 / Thunderbird 13 / SeaMonkey 2.10)
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. (error 891944)
NEXT
:"next"
: The cursor shows all records, including duplicates. It starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys).NEXTUNIQUE
:"nextunique"
: The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the lower bound of the key range and moves upwards.PREV
:"prev"
: The cursor shows all records, including duplicates. It starts at the upper bound of the key range and moves downwards (monotonically decreasing in the order of keys).PREVUNIQUE
:"prevunique"
: The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the upper bound of the key range and moves downwards.
Ejemplo
En este simple fragmento creamos una transacción, recuperamos un almacén de objetos y usamos un cursor para iterar todos los registros del almacén de objetos. El cursor no nos obliga a seleccionar los datos en base a una key
; podemos simplemente cogerlos todos. También tenga en cuenta que en cada iteración del bucle, puede tomar datos del registro actual bajo el objeto del cursor utilizando cursor.value.foo
. Para un ejemplo completo de funcionamiento, vea nuestro IDBCursor example (view example live.)
function displayData() {
var transaction = db.transaction(['rushAlbumList'], "readonly");
var objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var listItem = document.createElement('li');
listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year;
list.appendChild(listItem);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
};
}
Specifications
Specification | Status | Comment |
---|---|---|
Indexed Database API 2.0 La definición de 'cursor' en esta especificación. |
Recommendation |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | 23webkit 24 [1] |
10 moz 16.0 (16.0) |
10, partial | 15 | 7.1 |
Available in workers | (Yes) | 37.0 (37.0) | ? | (Yes) | ? |
Feature | Android | Firefox Mobile (Gecko) | Firefox OS | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 4.4 | 22.0 (22.0) | 1.0.1 | 10 | 22 | 8 |
Available in workers | (Yes) | 37.0 (37.0) | (Yes) | ? | (Yes) | ? |
[1]Be careful in Chrome as it still implements the old specification along with the new one. Similarly it still has the prefixed webkitIndexedDB
property even if the unprefixed indexedDB
is present.
See also
- Using IndexedDB
- Starting transactions:
IDBDatabase
- Using transactions:
IDBTransaction
- Setting a range of keys:
IDBKeyRange
- Retrieving and making changes to your data:
IDBObjectStore
- Using cursors:
IDBCursor
- Reference example: To-do Notifications (view example live.)