0

With a for loop I create 10 different Surfaces. By clicking on one of them, I want to get the content of this surface. But that s not working. instead I always get the content of the last created Surface (in my case it is 9). What do I have to change to get the content of the selected (clicked) surface and not the content of the last created?

here is my Code:

for (f = 0; f < 10; f++) {
        var draggable = new Draggable({
            xRange: [0, 1000],
            yRange: [0, 1000]
        });

        var surface = new Surface({
            size: [true, true],
            content: f,
            properties:{
                fontSize:'16px',
                cursor: 'pointer',
                borderRadius:'50px',
                backgroundColor: '#C0C0C0',
                border:'solid'
            }
        });

        surface.on("click",function(){alert(surface.content)});

        surface.pipe(draggable);        
        mainContext.add(draggable).add(surface);
  }
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
user2988098
  • 81
  • 1
  • 6
  • wrapping the creation of the surface and the event handler inside a function and calling the function will also fix this. But you should plus / check talves answer since it's right. – aintnorest Oct 15 '14 at 05:37
  • I should do an example also of the correct way to call a function binding it to the surface to show a better practice. – talves Oct 15 '14 at 17:17
  • yes, that would be nice – user2988098 Oct 16 '14 at 10:45

1 Answers1

1

The correct Surface is being selected. The issue is in the reference of the surface.content of the click function. The surface reference has been replaced each time until the last surface remains. Reference the current surface clicked using this.content in the function because this is bound to the current clicked surface in the click function.

Example code Here

for (f = 0; f < 10; f++) {
    var draggable = new Draggable({
        xRange: [0, 1000],
        yRange: [0, 1000]
    });

    var surface = new Surface({
        size: [true, true],
        content: f,
        properties: {
            fontSize: '16px',
            cursor: 'pointer',
            borderRadius: '50px',
            backgroundColor: '#C0C0C0',
            border: 'solid'
        }
    });

    surface.on("click", function () {
        alert(this.content)
    });

    surface.pipe(draggable);
    mainContext.add(draggable).add(surface);
}
talves
  • 13,993
  • 5
  • 40
  • 63
  • Manual hoisting by moving variable declarations outside `for` loop will remove ambiguity regarding block level scope. Just a note. – sabithpocker Oct 16 '14 at 15:25
  • You can see my comment above that I mention showing the best practices example, but this gives him the quick fix explanation for now. Thanks for the comment reminder. – talves Oct 17 '14 at 15:44