Search code examples
jqueryiife

Pass Object to Function Method


I have the following two immediately invoked functions:

var myCart = function() {
 var cart = [];

 var addToCart = function (item) {
   cart.push(item);
 }

 $(document).on('click', '.add-to-cart', function (e) {
   e.preventDefault();

   var item = $(this);
   addToCart ({
     ProductId: item.attr("data-id"),
     Name: item.attr("data-name"),
     Price: item.attr("data-price"),
     Quantity: 1
   });
 });

 return {
  addToCart: addToCart()
 }
}();

var MyOtherFunction = function (myCart) {
  $('.my-other-selector').click(function (e) {
    e.preventDefault();
    var item = $(this);
    myCart.addToCart ({
      ProductId: item.attr("data-id"),
      Name: item.attr("data-name"),
      Price: item.attr("data-price"),
      Quantity: 1
    });  
  });
}(MyCart);

I want to add an item to the cart from MyOtherFunction but no item gets added to the cart. How can I pass the item object into the addToCart method when it's called from MyOtherFunction?

Whats the best way to structure these functions so that I can call them from inside other functions?


Solution

  • The problem is here:

     return {
        addToCart: addToCart()
     }
    

    Replace the above with the following:

    return {
       addToCart : addToCart
    }
    

    You dont need () when assigning a function to a variable. Also you need to wrap your function in () like var myCart = (function() {})(); So your code become as follows:

     var myCart = (function() {
    
        var cart = [];
    
        var addToCart = function (item) {
           cart.push(item);
        }
    
        $(document).on('click', '.add-to-cart', function (e) {
            e.preventDefault();
    
            var item = $(this);
            addToCart ({
               ProductId: item.attr("data-id"),
               Name: item.attr("data-name"),
               Price: item.attr("data-price"),
               Quantity: 1
           });
        });
    
        return {
           addToCart: addToCart
        }
    
    })();