使用jQuery.each()时,是否可以使用非匿名函数?
我发现这个代码块特别长,很难理解:调用堆栈中充满了隐式函数和隐式添加的参数。换句话说,我想通过将在each中调用的函数与自身分离来澄清我的代码 看看这个例子:使用jQuery.each()时,是否可以使用非匿名函数?,jquery,refactoring,each,Jquery,Refactoring,Each,我发现这个代码块特别长,很难理解:调用堆栈中充满了隐式函数和隐式添加的参数。换句话说,我想通过将在each中调用的函数与自身分离来澄清我的代码 看看这个例子: $(xml).find('group').each(function () { var groupName = $(this).attr('name'); // There is here around 100 lines of codes I would like to split in // at least
$(xml).find('group').each(function () {
var groupName = $(this).attr('name');
// There is here around 100 lines of codes I would like to split in
// at least five functions, And I'm sure it is possible to use named functions
// instead of implicit ones, no ?
尝试传递函数引用
$(xml).find('group').each(myfun);
function myfun(i, item)
{
alert(item.id);
}
你也可以这样做:
$(xml).find('group').each(function(){
yourFunction();
});
请注意,回调函数接受indexInArray和ValueOfeElement参数。后者可以用来代替$(这个)谢谢注意,检查我的答案我添加了一个演示。+1。完全干净的抽象介绍正好在需要的地方。@CarlManaster,对不起?这里绝对没有引入抽象。。。除非
yourFunction
使用了与匿名函数one不同的参数集,在这种情况下,还可以取消匿名函数并对其命名。@Riduidel,代码已提取到其自己的命名函数中。这清楚地将调用从内部发生的混乱细节中分离出来,因此此块变得易于理解。可以对提取的块进行进一步的更改以使其更可读,但是该块不会受到影响;通过一个简单的抽象步骤:Extract方法,它已经变得清晰了。这样做意味着你的函数不会被迫接受一个与函数不相关的参数。理想情况下,您可以执行以下操作:$(xml).find('group').each(function(idx,item){yourFunction(item);});