2

I'm using events in JQuery to communicate between different JavaScript modules. So in one of the modules I have something like this:

$(window).on('updateStatusRequest', function(ev) { // Send updateStatus event after fetching data data = fetchData(); $(window).trigger('updateStatus', data); }); 

And this data fetch can potentially last long (it sends HTTP request outside) before finishing. Here's a problem I'm thinking about now - what if there are a lot of 'updateStatusRequest' triggered and the function didn't fetch data yet? I want to prevent multiple data fetches in that case so I'm thinking of something like this:

$(window).on('updateStatusRequest', function(ev) { $(window).off('updateStatusRequest', this); // Send updateStatus event after fetching data data = fetchData(); $(window).trigger('updateStatus', data); $(window).on('updateStatusRequest', this); }); 

So I want to turn callback off during its execution. Unfortunately the approach above don't work. What is the proper way to do that?

3
  • Hm..."fetchData is taking a long time"...before we continue on this, can you please assure me that you are NOT using synchronous requests? Commented Nov 13, 2015 at 19:39
  • I'm using JQuery's getJSON() to fetch data, I haven't found in its documentation whether is asynchronous or not but I'm assuming it is as it makes contact with the outside. Commented Nov 13, 2015 at 19:45
  • Alternatively to Howard's answer you can just wrap the content of your function in an if statement, that checks for a global variable, if (!fetching){fetching = true;...} and set fetching to false again on fetchData completion. Commented Nov 13, 2015 at 19:56

2 Answers 2

2

You need a callback when you add the event handler back in. Something like this should work:

$(window).on('updateStatusRequest', function(ev) { newFunction(); }); var newFunction = function (){ $(window).off('updateStatusRequest'); data = fetchData(); $(window).trigger('updateStatus', data); $(window).on('updateStatusRequest', function (){ newFunction(); }); } 

Although, I would probably use a promise instead of adding/removing the event handlers...

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

2 Comments

Thanks for that promise reference, will probably use that as it is more clear
no problem - promises are great, I use them all the time.
0

Use JQuery.ajax and turn async off

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.