sanders
sanders

Reputation: 10898

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

Upvotes: 1

Views: 74

Answers (3)

Vale
Vale

Reputation: 2032

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.

Upvotes: 2

Alex
Alex

Reputation: 1442

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(); });
    }
});

Upvotes: 2

Parth Shah
Parth Shah

Reputation: 2140

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

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

Upvotes: 1

Related Questions