[英]How to call a callback function from a different callback
Lets say I have some javascript as follows: 可以说我有一些JavaScript,如下所示:
$('#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. 在某些情况下,我想从
add
函数调用stop
函数。 The problem is that now the stop
function does not get called. 问题在于,现在没有调用
stop
函数。 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. 您要将匿名函数传递给fileupload,这意味着除非事先声明,否则您将无法引用它们。 Try declaring the two callbacks before with var, then you should be able to reference them
尝试在使用var之前声明两个回调,那么您应该可以引用它们
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? 尽管我不确定为什么您需要通过调用另一个函数来停止
add()
函数,但是您不能从中return
吗?
The add
method of fileuploader is a special case. fileuploader的
add
方法是一种特殊情况。 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. 在
add
里面, data.submit()
返回一个jQuery承诺( https://api.jquery.com/jQuery.ajax/#jqXHR ),它使您可以根据上传的状态来响应不同的情况。 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. 您似乎还以一种奇怪的方式使用了
stop
回调。 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. Fileuploader的
stop
选项是所有文件上传完成后的回调-我想不到您想要手动调用它的情况。 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. 如果您想阻止上传,则需要查看Parth Shah的答案中提到的
.abort()
方法。
$('#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();
},
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.