While building a carousel module for Joomla I am having 2 JavaScript issues I can’t get fixed. I’ve been trying for 2 days. Hopefully someone here can point out what I am doing wrong.
- I can’t get a boolean from a string
"0"
or string"1"
- And I can’t
JSON.parse()
to convert an object string to a JavaScript object
The situation:
To be able to have multiple instances on 1 page I am passing each modules individual settings (via php) to 1 object in my javascript file. Each module is 1 key value pair inside the object, the value being its own settings object. Basicly, this is how the JS recieves it:
const moduleSettings = { "103":{"items":3,"margin":5,"loop":"1","center":"0","responsive":"{0:{items:1}}"}, "105":{"items":3,"margin":5,"loop":"0","center":"1","responsive":"{0:{items:2}}"} };
Next I need to loop over each module to initialize the settings. This is done on ready using jQuery.
jQuery(document).ready(function() { // Loop over each module const modules = Object.keys(moduleSettings); for (const id of modules) { const target = "carousel-" + id; const params = moduleSettings[id]; // Callback to evaluate true/false params function eval(singleParam) { return params[singleParam] === "1"; }; // Initialize carousel jQuery(target).owlCarousel({ items: params.items, margin: params.margin, loop: eval("loop"), center: eval("center"), responsive: JSON.parse(params.responsive) }); }; });
The carousel properties items
& margin
are numbers. No problem there, but these are recieved as numbers from the start.
The problem:
- The properties
loop
¢er
should return a boolean, based on the callback functioneval()
. But they just return the string"0"
or"1"
. - The property
responsive
should return an object. But this still remains a string object"{...}"
.
The console error:
The first problem above does not block functionallity. It works, but I want to understand why my values are not booleans.
The second problem however causes console error and make the carousel not work. This is only IF responsive is not an empty string. When responsive is an empty string, it works. But I need the responsive setting.
I’ve been looking for the cause of this issue for 2 days now. It’s getting frustrating. Any pointers would be most helpfull. Thanks!
Advertisement
Answer
instead of using eval
function use can you below
jQuery(target).owlCarousel({ items: params.items, margin: params.margin, loop: !!params.loop, center: !!params.center, responsive: JSON.parse(params.responsive) });
For the second issue, you need to change the structure from your server side code to generate this module settings JSON. The responsive object is not a proper JSON. its should be like
responsive: {items:1}
or responsive: [{items:1}]
If you can post that code then I can tell you the change need to made there.