I am writing a custom module for quilljs. It is a simple text macro replacement tool.
ie type ".hi", it will replace it with "hello".
Originally I was calling quill.setSelection(...) within the text-change event. It wasn't working Codepen Original. Eventually I found this in the docs
Changes to text may cause changes to the selection (ex. typing advances the cursor), however during the text-change handler, the selection is not yet updated, and native browser behavior may place it in an inconsistent state. Use selection-change or editor-change for reliable selection updates." Quill setSelection API docs
So I reworked the code Codepen Revised. It works, but it sure is ugly and cursor updating after the text insertion looks weird. I cannot believe there isn't a better/idiomatic way to do this.
Quill.register("modules/quicktext", function (quill, options) {
let cache = "";
let finalcaret = null;
quill.on("editor-change", (eventName, ...args) => {
if (eventName === "text-change" && args[2] === "user") {
let [delta, oldDelta, source] = args;
console.log(source, delta);
let lastkey = delta.ops[delta.ops.length - 1]?.insert || "";
if (delta.ops[delta.ops.length - 1]?.delete) {
// handle delete key
cache = cache.slice(0, -1);
return;
}
if (lastkey && lastkey !== " ") {
cache += lastkey;
console.log("cache", cache, "lastkey", lastkey);
} else if (cache) {
// avoid initial call
console.log("cache", cache, "lastkey", lastkey);
reps.forEach((rep) => {
console.log("rep check", cache, rep[cache]);
if (rep[cache]) {
console.log("triggered");
let caret = quill.getSelection().index;
let start = caret - cache.length - 1;
quill.deleteText(start, cache.length, "api");
quill.insertText(start, rep[cache], "api");
//quill.update("api");
finalcaret = caret + rep[cache].length - cache.length;
console.log(
`caret at ${caret}, moving forward ${
rep[cache].length - cache.length
} spaces, to position ${
caret + rep[cache].length - cache.length
}.`
);
console.log("done trigger");
}
});
cache = "";
}
} else if (eventName === "selection-change") {
if (finalcaret) {
quill.setSelection(finalcaret);
finalcaret = "";
}
}
});
});
let reps = [
{ ".hi": "hello" },
{ ".bye": "goodbye" },
{ ".brb": "be right back" }
];
// We can now initialize Quill with something like this:
var quill = new Quill("#editor", {
modules: {
quicktext: {
reps: reps
}
}
});
I was able to figure out a solution based upon this issue. Not sure why this is necessary, but works but it does.
// quill.setSelection(finalcaret, 0) // this fails
setTimeout(() => quill.setSelection(finalcaret, 0), 1); // this works
Codepen FINAL
Related
I want to be able to change the value of a global variable when it is being used by a function as a parameter.
My javascript:
function playAudio(audioFile, canPlay) {
if (canPlay < 2 && audioFile.paused) {
canPlay = canPlay + 1;
audioFile.play();
} else {
if (canPlay >= 2) {
alert("This audio has already been played twice.");
} else {
alert("Please wait for the audio to finish playing.");
};
};
};
const btnPitch01 = document.getElementById("btnPitch01");
const audioFilePitch01 = new Audio("../aud/Pitch01.wav");
var canPlayPitch01 = 0;
btnPitch01.addEventListener("click", function() {
playAudio(audioFilePitch01, canPlayPitch01);
});
My HTML:
<body>
<button id="btnPitch01">Play Pitch01</button>
<button id="btnPitch02">Play Pitch02</button>
<script src="js/js-master.js"></script>
</body>
My scenario:
I'm building a Musical Aptitude Test for personal use that won't be hosted online. There are going to be hundreds of buttons each corresponding to their own audio files. Each audio file may only be played twice and no more than that. Buttons may not be pressed while their corresponding audio files are already playing.
All of that was working completely fine, until I optimised the function to use parameters. I know this would be good to avoid copy-pasting the same function hundreds of times, but it has broken the solution I used to prevent the audio from being played more than once. The "canPlayPitch01" variable, when it is being used as a parameter, no longer gets incremented, and therefore makes the [if (canPlay < 2)] useless.
How would I go about solving this? Even if it is bad coding practise, I would prefer to keep using the method I'm currently using, because I think it is a very logical one.
I'm a beginner and know very little, so please forgive any mistakes or poor coding practises. I welcome corrections and tips.
Thank you very much!
It's not possible, since variables are passed by value, not by reference. You should return the new value, and the caller should assign it to the variable.
function playAudio(audioFile, canPlay) {
if (canPlay < 2 && audioFile.paused) {
canPlay = canPlay + 1;
audioFile.play();
} else {
if (canPlay >= 2) {
alert("This audio has already been played twice.");
} else {
alert("Please wait for the audio to finish playing.");
};
};
return canPlay;
};
const btnPitch01 = document.getElementById("btnPitch01");
const audioFilePitch01 = new Audio("../aud/Pitch01.wav");
var canPlayPitch01 = 0;
btnPitch01.addEventListener("click", function() {
canPlayPitch01 = playAudio(audioFilePitch01, canPlayPitch01);
});
A little improvement of the data will fix the stated problem and probably have quite a few side benefits elsewhere in the code.
Your data looks like this:
const btnPitch01 = document.getElementById("btnPitch01");
const audioFilePitch01 = new Audio("../aud/Pitch01.wav");
var canPlayPitch01 = 0;
// and, judging by the naming used, there's probably more like this:
const btnPitch02 = document.getElementById("btnPitch02");
const audioFilePitch02 = new Audio("../aud/Pitch02.wav");
var canPlayPitch02 = 0;
// and so on
Now consider that global data looking like this:
const model = {
btnPitch01: {
canPlay: 0,
el: document.getElementById("btnPitch01"),
audioFile: new Audio("../aud/Pitch01.wav")
},
btnPitch02: { /* and so on */ }
}
Your event listener(s) can say:
btnPitch01.addEventListener("click", function(event) {
// notice how (if this is all that's done here) we can shrink this even further later
playAudio(event);
});
And your playAudio function can have a side-effect on the data:
function playAudio(event) {
// here's how we get from the button to the model item
const item = model[event.target.id];
if (item.canPlay < 2 && item.audioFile.paused) {
item.canPlay++;
item.audioFile.play();
} else {
if (item.canPlay >= 2) {
alert("This audio has already been played twice.");
} else {
alert("Please wait for the audio to finish playing.");
};
};
};
Side note: the model can probably be built in code...
// you can automate this even more using String padStart() on 1,2,3...
const baseIds = [ '01', '02', ... ];
const model = Object.fromEntries(
baseIds.map(baseId => {
const id = `btnPitch${baseId}`;
const value = {
canPlay: 0,
el: document.getElementById(id),
audioFile: new Audio(`../aud/Pitch${baseId}.wav`)
}
return [id, value];
})
);
// you can build the event listeners in a loop, too
// (or in the loop above)
Object.values(model).forEach(value => {
value.el.addEventListener("click", playAudio)
})
below is an example of the function.
btnPitch01.addEventListener("click", function() {
if ( this.dataset.numberOfPlays >= this.dataset.allowedNumberOfPlays ) return;
playAudio(audioFilePitch01, canPlayPitch01);
this.dataset.numberOfPlays++;
});
you would want to select all of your buttons and assign this to them after your html is loaded.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
const listOfButtons = document.getElementsByClassName('pitchButton');
listOfButtons.forEach( item => {
item.addEventListener("click", () => {
if ( this.dataset.numberOfPlays >= this.dataset.allowedNumberOfPlays ) return;
playAudio("audioFilePitch" + this.id);
this.dataset.numberOfPlays++;
});
How can I Get the Data Scanned by Barcode Reader in React Js and store it in state without input element
Here what I have done. Its working and give me the data scanned by Reader but here i used the input element and when I hide the input element then its not give me the data
Is it Possible to get it without input element and store it in react state
// #mui
import { Stack, TextField } from '#mui/material';
import { useState } from 'react';
export default function ScanCheckFrom() {
const [barcodeInputValue, updateBarcodeInputValue] = useState('');
function barcodeAutoFocus() {
document.getElementById('barcode')?.focus();
}
function onChangeBarcode(event: any) {
updateBarcodeInputValue(event.target.value);
}
function onKeyDown(event: any) {
if (event.keyCode === 13) {
console.log(barcodeInputValue);
}
}
return (
<Stack spacing={3}>
<TextField
autoFocus={true}
name="barcode"
value={barcodeInputValue}
onChange={onChangeBarcode}
id="barcode"
onKeyDown={onKeyDown}
onBlur={barcodeAutoFocus}
/>
</Stack>
);
}
From the look of your code, it seem your getting the barcode data on your web page. If that is the case, you can target the barcode tag with class,id,..., get the value and store it with your state management (useState,Redux,RTK,...).
If not get the value from codebar reader, and then store it.
I do not really get your issue!
Why do you need a input? Or maybe your getting the bar code through the input 🙄.
I think you need to use barcodescanner js for scanning event callback.
I am sharing you my working barcode scanning js file and function for get scan result inside event callback after barcode scan triggered in pc.
The barcodescanner.js file
(function ($) {
$.fn.scannerDetection = function (options) {
// If string given, call onComplete callback
if (typeof options === "string") {
this.each(function () {
this.scannerDetectionTest(options);
});
return this;
}
// If false (boolean) given, deinitialize plugin
if (options === false) {
this.each(function () {
this.scannerDetectionOff();
});
return this;
}
var defaults = {
onComplete: false, // Callback after detection of a successfull scanning (scanned string in parameter)
onError: false, // Callback after detection of a unsuccessfull scanning (scanned string in parameter)
onReceive: false, // Callback after receiving and processing a char (scanned char in parameter)
onKeyDetect: false, // Callback after detecting a keyDown (key char in parameter) - in contrast to onReceive, this fires for non-character keys like tab, arrows, etc. too!
timeBeforeScanTest: 100, // Wait duration (ms) after keypress event to check if scanning is finished
avgTimeByChar: 30, // Average time (ms) between 2 chars. Used to do difference between keyboard typing and scanning
minLength: 6, // Minimum length for a scanning
endChar: [9, 13], // Chars to remove and means end of scanning
startChar: [], // Chars to remove and means start of scanning
ignoreIfFocusOn: false, // do not handle scans if the currently focused element matches this selector
scanButtonKeyCode: false, // Key code of the scanner hardware button (if the scanner button a acts as a key itself)
scanButtonLongPressThreshold: 3, // How many times the hardware button should issue a pressed event before a barcode is read to detect a longpress
onScanButtonLongPressed: false, // Callback after detection of a successfull scan while the scan button was pressed and held down
stopPropagation: false, // Stop immediate propagation on keypress event
preventDefault: false // Prevent default action on keypress event
};
if (typeof options === "function") {
options = { onComplete: options }
}
if (typeof options !== "object") {
options = $.extend({}, defaults);
} else {
options = $.extend({}, defaults, options);
}
this.each(function () {
var self = this, $self = $(self), firstCharTime = 0, lastCharTime = 0, stringWriting = '', callIsScanner = false, testTimer = false, scanButtonCounter = 0;
var initScannerDetection = function () {
firstCharTime = 0;
stringWriting = '';
scanButtonCounter = 0;
};
self.scannerDetectionOff = function () {
$self.unbind('keydown.scannerDetection');
$self.unbind('keypress.scannerDetection');
}
self.isFocusOnIgnoredElement = function () {
if (!options.ignoreIfFocusOn) return false;
if (typeof options.ignoreIfFocusOn === 'string') return $(':focus').is(options.ignoreIfFocusOn);
if (typeof options.ignoreIfFocusOn === 'object' && options.ignoreIfFocusOn.length) {
var focused = $(':focus');
for (var i = 0; i < options.ignoreIfFocusOn.length; i++) {
if (focused.is(options.ignoreIfFocusOn[i])) {
return true;
}
}
}
return false;
}
self.scannerDetectionTest = function (s) {
// If string is given, test it
if (s) {
firstCharTime = lastCharTime = 0;
stringWriting = s;
}
if (!scanButtonCounter) {
scanButtonCounter = 1;
}
// If all condition are good (length, time...), call the callback and re-initialize the plugin for next scanning
// Else, just re-initialize
if (stringWriting.length >= options.minLength && lastCharTime - firstCharTime < stringWriting.length * options.avgTimeByChar) {
if (options.onScanButtonLongPressed && scanButtonCounter > options.scanButtonLongPressThreshold) options.onScanButtonLongPressed.call(self, stringWriting, scanButtonCounter);
else if (options.onComplete) options.onComplete.call(self, stringWriting, scanButtonCounter);
$self.trigger('scannerDetectionComplete', { string: stringWriting });
initScannerDetection();
return true;
} else {
if (options.onError) options.onError.call(self, stringWriting);
$self.trigger('scannerDetectionError', { string: stringWriting });
initScannerDetection();
return false;
}
}
$self.data('scannerDetection', { options: options }).unbind('.scannerDetection').bind('keydown.scannerDetection', function (e) {
// If it's just the button of the scanner, ignore it and wait for the real input
if (options.scanButtonKeyCode !== false && e.which == options.scanButtonKeyCode) {
scanButtonCounter++;
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Add event on keydown because keypress is not triggered for non character keys (tab, up, down...)
// So need that to check endChar and startChar (that is often tab or enter) and call keypress if necessary
else if ((firstCharTime && options.endChar.indexOf(e.which) !== -1)
|| (!firstCharTime && options.startChar.indexOf(e.which) !== -1)) {
// Clone event, set type and trigger it
var e2 = jQuery.Event('keypress', e);
e2.type = 'keypress.scannerDetection';
$self.triggerHandler(e2);
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Fire keyDetect event in any case!
if (options.onKeyDetect) options.onKeyDetect.call(self, e);
$self.trigger('scannerDetectionKeyDetect', { evt: e });
}).bind('keypress.scannerDetection', function (e) {
if (this.isFocusOnIgnoredElement()) return;
if (options.stopPropagation) e.stopImmediatePropagation();
if (options.preventDefault) e.preventDefault();
if (firstCharTime && options.endChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = true;
} else if (!firstCharTime && options.startChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = false;
} else {
if (typeof (e.which) != 'undefined') {
stringWriting += String.fromCharCode(e.which);
}
callIsScanner = false;
}
if (!firstCharTime) {
firstCharTime = Date.now();
}
lastCharTime = Date.now();
if (testTimer) clearTimeout(testTimer);
if (callIsScanner) {
self.scannerDetectionTest();
testTimer = false;
} else {
testTimer = setTimeout(self.scannerDetectionTest, options.timeBeforeScanTest);
}
if (options.onReceive) options.onReceive.call(self, e);
$self.trigger('scannerDetectionReceive', { evt: e });
});
});
return this;
}
})(jQuery);
And use of this js by doing this :
<script type="text/javascript">
$(document).scannerDetection({
timeBeforeScanTest: 200, // wait for the next character for upto 200ms
startChar: [120], // Prefix character for the cabled scanner (OPL6845R)
endChar: [13], // be sure the scan is complete if key 13 (enter) is detected
avgTimeByChar: 40, // it's not a barcode if a character takes longer than 40ms
onComplete: function(scanned_result, qty) {
console.log(scanned_result);
}, // main callback function
onKeyDetect: function(event) {
return false;
}
});
</script>
I am creating a website for a client at the moment, we decided an easy way to store "items" which will be passed down to a subdomain from the root would be to store them as cookies. This works perfectly fine in a normal browser, yet when I tested it on a native device browser it didn't work as smoothly. I am wondering where some of these problems may have been coming from and hoping you wonderful developers can lend a man a hand.
The idea is that on the frontend when a "Your Order" side drawer is pressed, a function runs grabbing the cookies and then sorts them into their specified content area's -> Downloadable Content, Requested Material and Bespoke Content. I have created two separate functions for this, one that was the original working piece and another more tailored and "good practice".
Tried having the "Value" of the cookie containing the values that need to be stored such as, [itemname],[itemlocation], [itemdescription], [itemtype].
The second function stores the item data in an object, the object is then JSON.stringified and iterated over in a for loop. This is then taken out of a string with JSON.parse() and further iterated over in an .each() iterating over the index(key) and val(value).
FIRST FUNCTION:
$('section#review-downloads a.toggle-btn').bind('click tap', function() {
let cookies;
let itemSplit;
var section = $('section#review-downloads');
if(section.hasClass('active')) {
section.removeClass('active');
setTimeout(function() {
$('section#review-downloads .selected-items div').find('p').remove();
}, 900);
} else {
section.addClass('active');
$.each(document.cookie.split(';'), function() {
cookies = this.split('=');
let trimId = cookies[0].trim();
vals = cookies[1].replace(/[\])}[{(]/g, '');
if(!(cookies[0] === "envFilter")) {
$.each(vals.split('[ ]'),function() {
itemSplit = this.split(',');
let itemId = trimId;
let itemName = itemSplit[0];
let itemUrl = itemSplit[1];
let itemType = itemSplit[2];
let itemDesc = itemSplit[3];
if(itemType === ' Downloadable Content ') {
$('<p id="selected-item-'+itemId+'"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .downloadable-content');
} else if (itemType === ' Requested Materials ') {
$('<p id="selected-item"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .requested-material');
} else if (itemType === ' Bespoke Content ') {
$('<p id="selected-item"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .bespoke-content');
}
});
};
});
}
return false;
});
THE SECOND FUNCTION (best practice)
$('div.support-item-wrapper div.order-add').bind('click tap', function() {
let id = $(this).data('id');
let name = $(this).data('title');
let file = $(this).data('file');
let type = $(this).data('type');
let desc = $(this).data('description').replace(/(\r\n|\n|\r)/gm, "");
let url = $(this).data('url');
let cookieVal = {
name: name,
file: file,
type: type,
desc: desc,
url: url
};
let string = JSON.stringify(cookieVal);
setCookie('product-'+id, string, 1);
});
$('section#review-downloads a.toggle-btn').bind('click tap', function() {
var section = $('section#review-downloads');
if(section.hasClass('active')) {
section.removeClass('active');
} else {
section.addClass('active');
let decoded_user_product;
cookie_values = document.cookie.split(';');
for(i = 0; i < cookie_values.length; i++) {
cookie_split = cookie_values[i].split("=");
cookie_key = cookie_split[0].trim();
cookie_value = cookie_split[1].trim();
// console.log(cookie_value);
if(cookie_key != "envFilter") {
decoded_user_product = JSON.parse(cookie_value);
}
$.each(decoded_user_product, function(index, val) {
// console.log("index:" + index + "& val:" + val);
if(index === "name") {
console.log(val);
} else if (index === "type") {
console.log(val);
} else if (index === "desc") {
console.log(val);
}
});
}
// console.log(decoded_user_product);
};
});
On Desktop, the results are perfectly fine. Each item is easily console.log()'able and has been easily sorted in the FIRST FUNCTION.
On Mobile, the same results were as to be expected. But after realising it hadn't worked I used chrome://inspect along with a lot of console.logs to come to the conclusion that I may be too inexperienced to understand what parts of my code are unable to run on a native browser.
Is there a way to generate document navigation using the HTML5 outline algorithm and CSS (and possibly JS) like TeX can generate a table of contents?
EDIT: Is there a way to display a linked outline of an HTML document without explicitly writing it? I'm thinking of something like \tableofcontents in TeX. So an empty <nav> tag would be filled with an unordered list of links to sections in the page, for example.
For a javascript who will create an automated toc from document outline, you will have to develop yours for the moment. [i found no copy-paste solution actually]
Study this :
http://code.google.com/p/h5o/
http://code.google.com/p/h5o/downloads/detail?name=outliner.0.5.0.62.js&can=2&q=
https://chrome.google.com/webstore/detail/html5-outliner/afoibpobokebhgfnknfndkgemglggomo
https://developer.mozilla.org/en-US/docs/HTML/Sections_and_Outlines_of_an_HTML5_document?redirectlocale=en-US&redirectslug=Sections_and_Outlines_of_an_HTML5_document
and this
http://blog.tremily.us/posts/HTML5_outlines/
http://projects.jga.me/toc/ ( jQuery plugin you might want to adapt )
[ADDON]
Suggested reading from user #unor : github.com/DylanFM/outliner sent me to this jsFiddle where there is another javascript startup.
Javascript
// See http://html5doctor.com/document-outlines/
// That article begins with info on HTML4 document outlines
// This doesn't do that yet, it just handles the HTML5 stuff beneath in the article
// I'm sure there are problems with handling that HTML5 stuff tho
var headingElements = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'],
sectioningElements = ['SECTION', 'ARTICLE', 'NAV', 'ASIDE'];
function makeOutline(root) {
var ar = [],
el = root.firstChild,
nested, hg;
while(el) {
// If it's a sectioning element, create a new level in the outline
if(sectioningElements.indexOf(el.tagName) > -1) {
nested = makeOutline(el);
if(nested.every(function(i){ return typeof i !== 'string'; })) {
nested.unshift('Untitled ' + el.tagName.toLowerCase());
}
ar.push(nested);
} else if(headingElements.indexOf(el.tagName) > -1) {
ar.push(el.textContent);
} else if(el.tagName === 'HGROUP') {
hg = undefined;
// Find the highest heading element within
// Use its text, otherwhise it's untitled
try {
headingElements.forEach(function(t) {
els = el.getElementsByTagName(t);
if(els.length) {
hg = els[0].textContent;
throw BreakException;
}
});
} catch(e) {}
if(!hg) {
hg = 'Untitled hgroup';
}
ar.push(hg);
}
el = el.nextSibling;
}
return ar;
};
var outline = makeOutline(document.body);
// This is just used for displaying the outline.
// Inspect the outline variable to see the generated array:
// console.log(outline);
function describeOutline(outline) {
var indentForDepth = function(depth) {
var str = '';
for(i=depth;i>0;i--) {
str += '\t';
}
return str;
},
childrenAreStrings = function(ar, depth) {
var depth = (depth && (depth + 1)) || 1;
return ar.map(function(item) {
if({}.toString.call(item)=='[object Array]') {
return childrenAreStrings(item, depth).join('\n');
} else {
return indentForDepth(depth) + '- ' + String(item);
}
});
};
// Make sure all items in ar are strings
return childrenAreStrings(outline).join('\n');
}
(document.getElementsByTagName('pre')[0]).textContent = describeOutline(outline);
Ok, first of all, sorry for my English.
I'm working in a web project that show suggests when I type something in the inputbox, but I want to use IndexedDB to improve the query speed in Firefox.
With WebSQL I have this sentence:
db.transaction(function (tx) {
var SQL = 'SELECT "column1",
"column2"
FROM "table"
WHERE "column1" LIKE ?
ORDER BY "sortcolumn" DESC
LIMIT 6';
tx.executeSql(SQL, [searchTerm + '%'], function(tx, rs) {
// Process code here
});
});
I want to do same thing with IndexedDB and I have this code:
db.transaction(['table'], 'readonly')
.objectStore('table')
.index('sortcolumn')
.openCursor(null, 'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
if (cursor.value.column1.substr(0, searchTerm.length) == searchTerm) {
// Process code here
} else {
cursor.continue();
}
}
};
But there's too slow and my code is buggy.. I want to know is there a better way to do this.
Thank for reply.
I finally found the solution to this problem.
The solution consist to bound a key range between the search term and the search term with a 'z' letter at the final. Example:
db.transaction(['table'], 'readonly')
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'), // The important part, thank Velmont to point out
'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
// console.log(cursor.value.column1 + ' = ' + cursor.value.column2);
cursor.continue();
}
};
Because I need to order the result, so I defined a array before the transaction, then we call it when we loaded all data, like this:
var result = [];
db.transaction(['table'], 'readonly')
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'), // The important part, thank Velmont to point out
'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
result.push([cursor.value.column1, cursor.value.sortcolumn]);
cursor.continue();
} else {
if (result.length) {
result.sort(function (a, b) {
return a[1] - b[2];
});
}
// Process code here
}
};
I have been experimenting with IndexedDB and I have found it to be very slow, added to that the complexity of its api and I'm not sure its worth using at all.
It really depends on how much data you have, but potentially it'd be worth doing the searching in memory, and then you can just marshall and un-marshall the data out of some kind of storage, either indexedDB or the simpler localStorage.
I have lost ~2 hours on the same problem and I have found the real problem.
Here the solution :
Replace IDBCursor.PREV by prev
(it's awful but this is the solution)
IDBCursor.PREV is bugged at the moment on Chrome (26/02/2013)