简体   繁体   中英

How to call a callback function from a different callback

Lets say I have some javascript as follows:

$('#bar').fileupload({
    baz: 2,
    baf: 6

    add: function(e, data){
       stop(e,data);
    },

    stop: function(e,data){
       console.log('I am Called');
    } 

});

From the add function i want to call the stop function in some situations. The problem is that now the stop function does not get called. How can I get this done?

Thanks

You're passing anonymous functions to fileupload, this means you have no way of referencing to them unless you declare them beforehand. Try declaring the two callbacks before with var, then you should be able to reference them

var stop = function(e,data){
    console.log('I am Called');
};

var add = function(e, data){
    stop();
};

$('#bar').fileupload({
    baz: 2,
    baf: 6, // you were missing a comma here
    add: add,
    stop: stop
});

Although I'm not sure why you would need to stop the add() function by calling another one, can't you just return from it?

EDIT: As others have pointed out, you shouldn't call the stop callback from add, my answer would be valid only in a more general case, please refer to the other answers or the documentation of fileupload to understand how to stop a download.

The add method of fileuploader is a special case. Inside add , data.submit() returns a jQuery promise ( https://api.jquery.com/jQuery.ajax/#jqXHR ) that allows you to respond to different situations based on the status of the upload. This will let you hook into a custom function for different responses.

$('#bar').fileupload({
    baz: 2,
    baf: 6,
    add: function(e, data){
       data.submit()
       .success(function(result, status, promise) { console.log('I am Called'); });
    }
});

You also seem to be using the stop callback in an odd way. Fileuploader's stop option is a callback for when all file uploading has completed - I can't think of a situation where you would want to call that manually. If what you would like to do is prevent the upload, you'll need to look at the .abort() method as referenced in Parth Shah's answer.

 $('#bar').fileupload({
    add: function(e, data){
       data.submit()
       .error(function(promise, status, error) { promise.abort(); });
    }
});

According to the documentation , here is how you should do it:

var jqXHR = null;
jqXHR = $('#bar').fileupload({
    ...,
    add: function (e, data) {
        jqXHR.abort();
    },
    ...
});

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