简体   繁体   中英

Can I add getJSON's done()-functions by callback?

On this code:

 function hello(){
     alert("hello");
 }
 function hi(){
     alert("hi");
 }

 jQuery.getJSON('foo.bar',function(data){
     if (data.foobar) {
         this.done(hello);
     }
     alert('callback done');
 }).done(hi);

and assuming this returns from foo.bar

{"foobar":true}

I like to have the alerts in this order:

  1. callback done
  2. hi
  3. hello

But I can not add a done() -function in the success -callback.

Have you a hint how I add a done() -function inside of the success -callback?

The jqXHR object is the third argument to the callback function:

jQuery.getJSON('foo.bar', function(data, textStatus, jqXHR) {
    if (data.foobar) {
        jqXHR.done(hello);
    }
    alert('calback done');
}).done(hi);

I don't think you should be trying to combine callbacks and done() handlers in the first place, let alone interweaving them like this. Just use one done() handler:

jQuery.getJSON('foo.bar').done(function (data) {
    hi();
    if (data.foobar) {
        hello();
    }
});

Or if you are worried about a failure in hi() preventing the rest from executing, you can pass them to done() separately:

jQuery.getJSON('foo.bar').done(hi, function (data) {
    if (data.foobar) {
        hello();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM