JavaScript event handling code get's called multiple times

百般思念 提交于 2020-12-15 05:47:18

问题


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.


回答1:


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




回答2:


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);


来源:https://stackoverflow.com/questions/64706859/javascript-event-handling-code-gets-called-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!