如果我有这样的链接函数,并希望在for循环中运行它们......如何在调用链式回调函数时确保维护上下文?
您可以在下面看到,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);
});
}
...
我正在使用RaphaelJS,顺便说一句。