Question

I'm trying to learn the basics of IndexedDB by creating a trivial notepad application. I'm having difficulties using an ordered list in this environment.

The feature I'm not sure how to implement is having an ordered list of notes.

I first tried implementing the notepad application in WebSQL, and I found it quite easy to select the notes like this:

select * from notes order by position

And when inserting a note at a specified position, I first did ...

update notes set position = position + 1 where position >= insert_position

... to shift each note to make space for the new note at position insert_position.

But I saw that WebSQL is actually deprecated.

What are the possibilities to achieve such a feature in IndexedDB? I don't fully understand how to create an ordered list in an environment such as IndexedDB since a quick query like the above is not applicable.

As a side note, I know it's possible to store an array in IndexedDB, but then I would just have one record which I'm using each time. I'm rather looking for a way to somehow have an ordered list of all records (each record representing a note), and to be able to update the ordering (like the shifting query above).

Could someone shed some light on the IndexedDB way of an ordered list?

Was it helpful?

Solution

As with many things there are a few ways to crack this nut.

If you were creating an app that orders notes based on creation time, it would be as simple as using an auto-incrementing key (this flag is specified on objectStore creation). Note one would have the id (aka primaryKey) of 1, the second 2 and so forth. This would use the default keyPath, so you could open up a cursor without having to create an index.

To order notes by something that could change, such as modified on time, you'd create an index on that field and be sure to specify it when adding or putting objects. You would open up a cursor with a lower bound of, say 0 (lexicographically ordered keys means this comes before all strings) and leave the upper bound open. You'd then cursor across each row one by one firing onsuccess handlers until you exhaust your cursor and it returns null in event. target.result.

It sounds like you might be looking to have a field such as "position" and order on that. That's totally doable with a regular index and cursor, as above. One note of advice would be to make position field a floating point number rather than an integer as with the former you can update the order without having to alter any other rows (position n = ( ( position 1 + position 2 ) / 2 )).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top