1

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++');
});

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Wow, this is super clever and works just as expected. I didn't think of passing data like that. Checked out the on() documentation on jQuery's website and it makes sense. Thanks again.
@James Yeah, I don't use it often, but in cases like these it comes in quite handy :)
I noticed an issue with this implementation. Now that it is part of a function, if there are 2 rows of products in the cart, and I click increase on one row, it changes both rows instead of just the one. Any idea?
@James this still references the element that was clicked, so you should only update that one in particular.
Hmm, it was doing both rows. I will have to look into that. Another question. Say I want to pass in data such as productPrice: price + linePrice.. I am unable to do that. Is there a way to pass that in as a string, but in the function make it into an operation?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.