Javascript 将值从for循环传递给链式函数
如果我有链式函数,并且希望在for循环中运行它们。。。调用链式回调函数时,如何确保上下文得到维护 您可以在下面看到,Javascript 将值从for循环传递给链式函数,javascript,callback,raphael,Javascript,Callback,Raphael,如果我有链式函数,并且希望在for循环中运行它们。。。调用链式回调函数时,如何确保上下文得到维护 您可以在下面看到,console.log(children[i])在for循环启动时输出一个值,但在回调中未定义: api.drawConnection = function (fromNode, toNode, bool) { if (bool) { var children = fromNode.getChildren(); var node = nul
console.log(children[i])
在for循环启动时输出一个值,但在回调中未定义:
api.drawConnection = function (fromNode, toNode, bool) {
if (bool) {
var children = fromNode.getChildren();
var node = null;
var valX, valY = 0;
node = fromNode;
valX = 50;
valY = 35;
//resize all node distances as children gets bigger...
if (children.length > 0) {
for (var i = 0; i < children.length; i++) {
valX+=50;
var connectPath = canvas.path("M " + node.x + " " + node.y + " z");
log(children[i]); //outputs value
children[i].set.animate({
cx: node.shape.attrs.cx-valX/children.length,
cy: node.shape.attrs.cy+valY,
x : node.shape.attrs.cx-valX/children.length,
y: node.shape.attrs.cy+valY
}, 1000, "backOut", function () {
log(children[i]); //outputs undefined
connectPath.animate({
path: ("M " + fromNode.shape.attrs.cx + " " + (fromNode.shape.attrs.cy+10) + " L " + children[i].shape.attrs.cx + " " + children[i].shape.attrs.cy + " z")
}, 1000);
});
}
...
api.drawConnection=函数(fromNode、toNode、bool){
如果(bool){
var children=fromNode.getChildren();
var节点=null;
var-valX,valY=0;
node=fromNode;
valX=50;
谷=35;
//随着子节点变大,调整所有节点距离。。。
如果(children.length>0){
对于(变量i=0;i
顺便说一句,我使用的是RaphaelJS。需要一个闭包,当您的回调启动时,for循环将很长时间完成,因此
I
不是您所期望的be@charlietfl我想了想。我对闭包的概念是全新的……我该如何编辑它使其成为闭包形式呢?一种方法是使用(函数(I))将所有内容包装在循环中{/*code*})(i);
@charlietfl这是可行的!但是为什么呢?我一直在阅读闭包的相关内容,这里:,为什么这样做毫无意义。为什么要将i
传递给自执行函数包装器?因为当你将它作为参数传递时,它现在是该函数内部的一个孤立变量