2
I’m studying a little jQuery and I found that interesting.
The problem is I don’t quite understand.
What is the Deferred Object in jQuery for?
How this can become useful when using jQuery?
2
I’m studying a little jQuery and I found that interesting.
The problem is I don’t quite understand.
What is the Deferred Object in jQuery for?
How this can become useful when using jQuery?
1
What good is?
It server for asynchronous processing treatment. For example:
var timer;
(function process() {
$('#output').html('Estou carregando angula coisa…');
var deferred = $.Deferred();
/* Aqui vc define um tempo de notificacao no caso 1 segundo */
timer = setInterval(function() {
deferred.notify();
}, 1000);
/* Esse timeout simula o tempo de resposta */
setTimeout(function() {
clearInterval(timer);
deferred.resolve();
}, 10000);
return deferred.promise();
})().then(function() {
/* Esse cara é chamado quando termina o processamento assíncrono */
$('#output').html('Terminei de carregar. Agora vou fazer algo!!!');
}, null, function() {
/* Esse cara é notificado a cada segundo enquanto o processamento não for finalizado */
$('#output').html($('#output').html() + '.');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output" />
In this example we have a routine that is executed for a certain time. This routine can be compared to the loading of a page via js. Imagine that you need to download a json-shaped file from any page. When you finish you will need to run something. There is the possibility for you to perform synchronous processing, but the message below may occur that can change from browser to browser.
When to use?
You should always use any system routine that is treated asynchronously and you need the page returned to perform a specific treatment. For example, in the load of an image via js or even in the load of another js that needs to be asynchronous.
Excellent, wonderful :)
Browser other questions tagged jquery
You are not signed in. Login or sign up in order to post.
There’s an answer here that talks about this method, and some examples, I’ll look up and if I find link.
– Edilson
In advance, the deferred Object consist of a series of callbacks run in series, and function as rows, one does not run while another has not finished.
– Edilson
An explanatory answer - http://answall.com/questions/82363/howto function the when-e-then-aligned
– Edilson
And you can also use this to see other examples - http://answall.com/search?q=%22%24.when%22
– Edilson
There is also this question, which I believe to be the same doubt - http://answall.com/questions/16921/commond-learn-learn-a-usar-promessas-em-javascript/16929#16929
– Edilson