0

I need your help. I'm currently working with a modal lib in JavaScript to display a modal for my customers:

https://github.com/vodkabears/Remodal/tree/1.1.1

Unfortunately my event handling in case the user clicks a button don't works like expected. When you take a look into the manual, you can see under the point Events the following event handler:

$(document).on('cancellation', '.remodal', function () {
  console.log('Cancel button is clicked');
});

This one get's triggered for example when the cancel button get's pressed. Because I'm using one popup for multiple things, I need to attach the event handler to the call directly. So first I've wrote a function that opens the popup:

function openRemodal( remodalId ) {
    let remodal = $( `[data-remodal-id=${remodalId}]` );

    remodal.remodal().open();

    return remodal; // <- added to handle events
}

I can call this function that way:

openRemodal( 'information-remodal' ); 

To get an event handling done, I've now returned the remodal in the function and re-wrote my call:

openRemodal( 'information-remodal' ).on( 'cancellation', function () {
    alert( 'Test' );
} );

This seems to work but somehow when I repeat the opening of the popup and pressing the button, the alert get's shown multiple times increased by any new opening.

I'm not sure why this happens and why. Can you please help me get this working? I just want to call any function in there once - any time.

2 Answers 2

1

JQuery has a .one method ... try using that in place of .on. The callback should run only once. https://api.jquery.com/one/

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

1 Comment

Works! Thanks mate.
1

On each time when you open model you attach function to cancelation event. so add new function and you never remove it. after first time you have one, then you have two... etc.

just attach it once, or remove it after handling event.

const modal = openRemodal( 'information-remodal' )
const handler = () => {
    alert( 'Test' );
    modal.off('cancellation', handler);
}

modal.on( 'cancellation', handler);

2 Comments

Which solution is better? The below one with .one or your one? What would you say?
you shouldn't add multiple times on each open new handler to tracking closing. it should be done once on creation modal, or loading page. if you have to add it durgin phase of opening modal then is just clean remove it. In your case is not matter because probably you don't open and close your modal 1000 times. So uppon you. But just for know this behaviour follows from attaching multiple handler to the same event.

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.