I am using Slate V1.* to develop a Shopify Theme. I have a js file for a specific template:
collection.bundle-product.js
// Get bundle total cost
function getTotal(data) {
var total = 0;
var products = [];
data.forEach(function (item) {
products.push({ price: item.price });
});
products.forEach(function (product) {
total += product.price;
});
return total;
};
I am trying to call the getTotal function from within the collection.bundle-product.liquid template file:
(function () {
var bundleValue = getTotal(productCollection);
})();
I am getting the following console error:
Uncaught ReferenceError: getTotal is not defined
I can confirm the JS file is loaded correctly. Any ideas what is going wrong?
2
Answers
Turns out the way JS is bundled with Slate/Webpack the functions have no global scope. So I have attached it to the window object like so:
I can then call it from a liquid template file like so:
The function is getting executed before the js file loads. What you can do is wait for the function to be available and then execute the function.