sjo*_*urg 48 javascript jquery function callback
我有以下功能.
function ChangeDasPanel(controllerPath, postParams) {
$.post(controllerPath, postParams, function(returnValue) {
$('#DasSpace').hide("slide", { direction: "right" }, 1000, function() {
$('#DasSpace').contents().remove();
$('#DasSpace').append(returnValue).css("display", "block");
$('#DasSpace').show("slide", { direction: "right" }, 1000);
});
});
};
Run Code Online (Sandbox Code Playgroud)
但我希望能够像这样称呼它
ChangeDasPanel("../Home/Test", {} ,function (){
//do some stuff on callback
}
Run Code Online (Sandbox Code Playgroud)
如何在我的函数中实现对回调的支持?
Tom*_*lak 75
function ChangeDasPanel(controllerPath, postParams, f) {
$.get(
controllerPath,
postParams,
function(returnValue) {
var $DasSpace = $('#DasSpace');
$DasSpace.hide(
"slide", { direction: "right" }, 1000,
function() {
$DasSpace.contents().remove();
$DasSpace.append(returnValue).css("display", "block");
$DasSpace.show("slide", { direction: "right" }, 1000);
}
);
if (typeof f == "function") f(); else alert('meh');
}
);
};
Run Code Online (Sandbox Code Playgroud)
您可以像JavaScript中的任何其他对象一样传递函数.传入回调函数很简单,您甚至可以在$.post()通话中自行完成.
您可以决定是否要将回调作为回调的一部分进行$.post()调用,或者单独调用.
Uzb*_*jon 22
你知道全局变量和函数都是邪恶的,所以为什么不把你的内容放到jQuery命名空间中:
$.extend({
myFunc : function(someArg, callbackFnk){
var url = "http://example.com?q=" + someArg;
$.getJSON(url, function(data){
// now we are calling our own callback function
if(typeof callbackFnk == 'function'){
callbackFnk.call(this, data);
}
});
}
});
$.myFunc(args, function(){
// now my function is not hardcoded
// in the plugin itself
});
Run Code Online (Sandbox Code Playgroud)
阅读这篇文章以便更好地理解:在jQuery中创建回调函数
Ala*_*lum 14
如果我理解正确,就像设置另一个参数并将变量调用为函数一样简单:
function foo(mycallback) {
mycallback();
}
Run Code Online (Sandbox Code Playgroud)
red*_*are 11
为什么不使用可以传递给函数的对象.它更像jQuery,它可以节省你的x命名参数很难维护,因为当你超过3个参数时它会变得笨拙.
例如
function callingFunction(){
var fnSettings: {
url: someUrl,
data: params,
callback : function(){}
};
yourFunction( fnSettings );
}
function yourFunction( settings ) {
$.post( settings.url, settings.data, settings.callback );
}
Run Code Online (Sandbox Code Playgroud)