Using expandable cards: how to avoid summing up of click events when returning to the page again?


#1

I am using expandable cards in a list that are dynamically generated from an ajax request retrieving a json file… this cards has infinite loading implemented so I can load the cards by chunks of 10 cards when scrolling down…

When I open the card I need to load dynamic content inside the card so I am using:

$(document).on('card:opened', '.card', function(el) {
...
alert('card is opened');
//... dynamic content... to load
});

I use this above instead of:

$(".card").on("card:opened", function(el) {
...
alert('card is opened');
});

because when using infinite scroll to load more cards I cannot attach the card:opened event to the new cards because it is not working for those so I have to use this:

$(document).on('card:opened', '.card', function(el) {
...
alert('card is opened');
});

So I use $(document).on(‘card:opened’, ‘.card’, function(el) … to attach the card:opened event to the new cards.

PROBLEM:

If I go back to the previous page and enter again to the page where the list of cards are generated, then when I open the card again then the ‘card:opened’ is running more than one and execute the event twice or more depending how many times I go back to the previous page and return…

If there a way to avoid this summing up of events using this:

$(document).on('card:opened', '.card', function(el) {
...
alert('card is opened'); // running more than one when returning page...
});

I tried to use this below when card:closed but when returning to the page and I open the cards then the event card:opened does not work anymore… or it is unbinded…

 $(document).off('card:opened', '.card');

is there any solution for this?
thanks


#2

I found a solution but I do not know if this is perfect but I add the following code to the data return function and now the summing up of events it does not happen anymore:

<script>
  return {
    data: function() {

      $(document).off('card:beforeopen', '.card');
      $(document).off('card:opened', '.card');
      $(document).off('card:close', '.card');
      $(document).off('card:closed', '.card');
...
});

pageInit: function(e, page) {
...
$(document).on('card:beforeopen', '.card', function(el, prevent) {
...
});

$(document).on('card:opened', '.card', function(el) {
...
});


...
});