David
David

Reputation: 509

reinitiate jquery plugin after ajax, causes events to fire multiple times

I have a query plugin I'm working on and I certain functions after ajax content has loaded. The problem is that let's say I re-initiate it 15 times, a click event will then fire 15 times when it's only clicked once.

Is there a way so it doesn't keep piling up? I'm calling addToCart onload and also from itemDetail after the ajax return

thanks!

function addToCart()
{
  $(options.add_to_cart).click(function ()
  {
    event.preventDefault();
    var id = $(this).attr('id');

    store_item_id_val = id.replace('store-item-id-', '');
    var quantity = $('.quantity-' + store_item_id_val);

    if (quantity.val() < 1)
    {
      showError('Please enter a quantity of 1 or more.');
      $(quantity).val(1);
      return this;
    }

    $.post($(this).attr('href'),
    { store_item_id: store_item_id_val, quantity: quantity.val() },
      function (data)
      {
        var result = jQuery.parseJSON(data);
        renderCart(result);
      });
  });

  return this;
}

function itemDetails()
{
  $('.item-details').click(function ()
  {
    event.preventDefault();

    var url = $(this).attr('href');

    $.getJSON(url, function (result)
    {

      $('.modal-title').empty().html(result.title);
      $('.modal-content').empty().html(result.html);
      $('#modal').slideDown(100);
      $('.ui-button').button();
      addToCart();
      $('.modal-close').click(function ()
      {
        event.preventDefault();
        $('#modal').hide();
      });
    });
  });

Upvotes: 0

Views: 671

Answers (1)

Erik Philips
Erik Philips

Reputation: 54618

Based on the code you provided, I would probably say that you have some other code calling itemDetails(). Each time itemDetails() is called, it ADDS another event handler for click to your .item-details. You may want to instead do:

$(document).ready(function()
{
  $('.item-details').click(function ()
  {
    event.preventDefault();

    var url = $(this).attr('href');

    $.getJSON(url, function (result)
    {

      $('.modal-title').empty().html(result.title);
      $('.modal-content').empty().html(result.html);
      $('#modal').slideDown(100);
      $('.ui-button').button();
      addToCart();
      $('.modal-close').click(function ()
      {
        event.preventDefault();
        $('#modal').hide();
      });
    });
  });
});

This would put the event handler on your .item-details classed items, and only fire the events once. If you have dynamic .item-details added and removed you probably should use:

$('.item-details').live('click', function() ...

Upvotes: 1

Related Questions