Event delegation only once, in a 'dynamic' scenario

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 multiple times, and as a consequence the hello() function executes the same number of times.

How do I, given that 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 modal?

    
asked by anonymous 17.08.2017 / 17:16

1 answer

2

You did not give too much context to the rest of the code, 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 (not ideal but it's a way to do it). This will only work after ajax has run once.

You can probably also use .one( which is jQuery's way to run an event handler only once.

It would look like this:

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);
  });
});
    
17.08.2017 / 17:19