I wanted to clean up my code and move some of the helper functions into another file. The code worked fine until I moved the following two functions into a backend file. If I copy the functions back into the file it will tell me that those two functions are already declared indicating that it is imported correctly and I've tested (via console.log) that both functions run properly but the .sort() seems to ignore the results and does nothing with it.
If I copy the functions back and delete the import line (basically revert it to the way it originally was) it works fine.
export function sortColors(a, b) {
let aHSL = hexToHSL(a.hex)
let bHSL = hexToHSL(b.hex)
if (aHSL[1] < bHSL[1]) {
return -1;
}
if (aHSL[1] > bHSL[1]) {
return 1;
}
if (aHSL[0] < bHSL[0]) {
return -1;
}
if (aHSL[0] > bHSL[0]) {
return 1;
}
if (aHSL[2] < bHSL[2]) {
return -1;
}
if (aHSL[2] > bHSL[2]) {
return 1;
}
return 0;
}
export function hexToHSL(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
var r = parseInt(result[1], 16);
var g = parseInt(result[2], 16);
var b = parseInt(result[3], 16);
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b),
min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
s = s * 100;
s = Math.round(s);
l = l * 100;
l = Math.round(l);
h = Math.round(360 * h);
return [h, s, l]
}
The sort is imported and called via the following code:
import {hexToHSL, sortColors} from 'backend/colorOptionsFunctions'
//BUNCH OF OTHER CODE
setColorData.sort(function(a,b){
return sortColors(a, b)
})
I don't think you need to do anything special when calling the function so what is wrong? is this something on Wix's end?
When calling backend functions (Web Modules in a .jsw file) from the frontend, you need to handle the returned Promise. See the article Corvid Web Modules: Calling Server-Side Code from the Front-End for full details on calling Web Modules.