Magento – Refresh minicart in javascript file

cartjavascriptmagento-2.1requirejs

I have a javascript file like this:

jQuery(document).ready(function($){
    var mainWindown = top.document;
    test = {
        teesping_vesrion : '1.0.0',
        mainStuff : function(){
            var vars = {};
            this.doStuff();
            //refesh mini cart here
        },
        doStuff : function(){
         ......
        }
    )
})

i want to reload the minicart in my mainStuff function, but i dont know how to integrate the below code to my javascript file, which is to reload minicart:

<script>
  require([
    'Magento_Customer/js/customer-data'
  ], function (customerData) {
    var sections = ['cart'];
    customerData.invalidate(sections);
  });
</script>

Best Answer

As Rakesh said in the comment you can trigger the content to be updated:

miniCart = $('[data-block=\'minicart\']');
miniCart.trigger('contentUpdated');

You can see this used in minicart.js

Notes

Related tip: To run your script on page load it's better to use domReady! as a dependency rather than use the jquery document ready method. domReady! makes sure other dependant scripts are aware of the dom ready requirement.

Related Topic