1

Possible Duplicate:
Event handlers inside a Javascript loop - need a closure?

I am a new learner in kineticjs. I meet some complex javascript closure problem while i using kinetic.shape to draw a continuous line like

  for(var i = 0; i < 4; i++)
  {
    var y_position = data[i];
    context.lineTo(i*x_position, y_position);
  }

It is too many layer in my case, i had changed my code many times but still can't get my expected result.Could anyone help me?

    for(var i = 0; i < 4; i++){ 
        var y_position = data[i];
        //document.write("<br/>"+y_position);  (it print 0 1 2 3)
        var line = new Kinetic.Shape({
            drawFunc: function() {
                var context = this.getContext();
                context.lineTo(i*x_position, y_position);
                this.stroke(context);
                //document.write("<br/>"+y_position);  (it print 3 3 3 3)
                },

                stroke: lineColor,
                strokeWidth: 1
            });
            layer.add(line);
    }
Community
  • 1
  • 1
yuki
  • 11
  • 1
  • Thanks for your reply. ya, i had been seen closure example and I try to apply to my code, such as drawFunc: function(value) { return function (){ context.lineTo(value*x_position, y_position);}(i),stroke: lineColor, strokeWidth: 1});layer.add(line);} but it still does not work, Can you clearly define the where is the problem? And there is some structure limitation in the drawFunc also, the context cannot be inherit to next iteration. – yuki Nov 14 '12 at 14:45
  • They key thing you need to do is make sure that `y_position` is passed as a parameter into the function that returns the actual function. – Pointy Nov 14 '12 at 15:31

0 Answers0