skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    window.themeBundles = {
      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 can then call it from a liquid template file like so:

    themeBundles.getTotal(productCollection)
    

  2. 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.

    findTotal = function(){
      if(typeof(getTotal)!='function'){
        console.log('getTotal not found');
        setTimeout(findTotal, 50);
      }
      else{
        console.log('getTotal function found');
        bundleValue = getTotal(productCollection);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search