Event delegation only once, in a 'dynamic' scenario

Asked

Viewed 88 times

2

I have a function hello() whose argument is the return of an ajax call:

function hello(msg) {
    alert(msg);
}

$.ajax({
    url: 'example.com',
    data: data
  }).done(function(resp) {
     // abre_modal
     // apenas no fecho (click close) da modal é que eu quero que a função abaixo seja executada
     $('#myModal').on('hide.bs.modal', function() { hello(resp); });
  });

But the above scenario causes a problem, the event is delegated several times, and as a consequence the function hello() is executed the same number of times.

How do I, considering I only want to delegate the event once, but the resp is dynamic, so that the function is executed only once, as well as the delegation of the event click close of the modal?

1 answer

2


You didn’t give the rest of the code much context, but you could do something like this:

var resposta = '';
$('#myModal').on('hide.bs.modal', function() {
  hello(resposta);
});

$.ajax({
  url: 'example.com',
  data: data
}).done(function(resp) {
  resposta = resp;
});

So you have the globally accessible variable (it’s not ideal but it’s a way to do it). It will only work after ajax has run once.

You can probably use the .one( which is the jQuery way to run an Event Handler only 1 time.

Would that be:

function hello(msg) {
  alert(msg);
}

$.ajax({
  url: 'example.com',
  data: data
}).done(function(resp) {
  // abre_modal
  // apenas no fecho (click close) da modal é que eu quero que a função abaixo seja executada
  $('#myModal').one('hide.bs.modal', function() {
    hello(resp);
  });
});

  • That’s okay because the modal only opens when ajax is done(). In the meantime, I’ve managed: $('#myModal').off('hide.bs.modal').on('hide.bs.modal', function() {...});. But I’ll take yours for sure. Thank you.

  • @Hulahula also foreheads with .one(, jQuery has to run Event handlers only once

  • Ha good, I didn’t know that no

Browser other questions tagged

You are not signed in. Login or sign up in order to post.