我想你的問題有趣的部分是如何重構,而不會失去對閉包變量的訪問。這裏是我的建議:
版本之一:嵌套,以封鎖和變量訪問:
var a;
$('a.edit').click(function() {
var b;
$.ajax({
success: function() {
var c;
$(new_form).submit(function() {
var d;
$.ajax({
success: function(data) {
// a,b,c,d are all visible here.
// note that a references the same object for all calls of the success function, whereas d is a different variable for each call of submit.
// this behaviour is called closure: the 'enclosed' function has access to the outer var
}
})
})
}
})
})
版本二:不嵌套的,但沒有封鎖和不變量訪問:
var a;
$('a.edit').click(onEdit);
var onEdit = function() {
var b;
$.ajax({success: onEditSuccess});
};
var onEditSuccess = function() {
var c;
$(new_form).submit(onSubmit);
};
var onSubmit = function() {
var d;
$.ajax({success: onSubmitSuccess});
}
var onSubmitSuccess = function(data) {
// a is visible (global var)
// b,c,d NOT visible here.
};
第三版:嵌套較少並且具有未命名的函數和參數以訪問閉合變量:
var a;
$('a.edit').click(function(){onEdit(a)});
var onEdit = function(a) {
var b;
$.ajax({success: function(){onEditSuccess(a,b)}});
};
var onEditSuccess = function(a,b) {
var c;
$(new_form).submit(function(){onSubmit(a,b,c)});
};
var onSubmit = function(a,b,c) {
var d;
$.ajax({success: function(data){onSubmitSuccess(data,a,b,c,d)}});
}
var onSubmitSuccess = function(data,a,b,c,d) {
// a,b,c,d are visible again
// nice side effect: people not familiar with closures see that the vars are available as they are function parameters
};
來源
2010-09-29 08:47:42
tec
Re使用$()。live() - 要小心,因爲提交事件在Internet Explorer中不會冒泡。據說jQuery修復了這個問題,但是我發現我不得不綁定到submit按鈕的click事件,這顯然不是最好的解決方案。 – lonesomeday 2010-09-29 08:42:03
我總是遠離過度嵌套的構造。再加上任何體面的IDE都不需要記錄右括號,看起來真的很醜! – 2011-05-05 16:41:21