James
James

Reputation: 115

Passing value into function and variable scope in JQuery

Link to code example:

http://jsfiddle.net/99Shr/

This code works for a given click handler, and $(this) takes on the particular class.

I am attempting to take the code that is inside the click function and put it into it's own function. The reason I want to do this is because I would like to replace quantity-- with quantity++ depending on which click handler is called. The issue I am running into is that the variables when called in the function are undefined since $(this) is window.

I am well aware that I may be doing this wrong to achieve what I want and am open to learning a better way to achieve it.

function price(change) {
   return change;
}

$('.cart-item-decrease').click(function(){
   price('quantity--');
});

or

$('.cart-item-increase').click(function(){
   price('quantity++');
});

Upvotes: 1

Views: 1030

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173562

You can customise the event handler registration so that additional data gets sent to your function:

function myClickHandler(e)
{
    // ...
    quantity += e.data.increment;
    // ...
}

$('.cart-item-increase').on('click', null, {
  increment: 1
}, myClickHandler);

$('.cart-item-decrease').on('click', null, {
  increment: -1
}, myClickHandler);

Here, the increment property gets sent to myClickHandler as e.data.increment.

Upvotes: 5

Related Questions