Reputation: 4816
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?
Upvotes: 2
Views: 121
Reputation: 4739
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...
Upvotes: 2