Question

I have a surface where i draw some kind of dynamic image based on the data from my backend, on click of a certain area, i want different data to be published. but my following code always takes last data drawn to publish.

function renderICD() {
    var totalx=1200;
    var totaly=1000;
    var xOffset = 150;
    var yOffset = 20;

    surface = dojox.gfx.createSurface("icdTab",totalx+2,totaly+2);
    var grid = surface.createGroup();
    var step = 1;
    var xyHolder = {};
    var group = grid.createGroup();

    for(var ii=0;ii<2;ii++)
    {
         var x = (step-1) * (75+85);
         step++;

         var group = grid.createGroup();

         group.createRect({x:xOffset+x+33, y:yOffset+20+90, width: 10, height: 10}).setFill([255, 255, 255, 0.9])
            .setStroke({color:'black' , width:2});


              dojo.connect(group.getEventSource(),"onclick",function(e) {
                       var internal = ii;
                       alert("publishing "+internal);
               //shape was clicked, now do something!
                        });

         grid.createText({x:xOffset+x+33, y:yOffset+20+80, text:ii,align:"middle"})
            .setFill('red')
            .setFont({size: '10px',weight: "bold"});
    }
} 

As i understand, only 1 instance of function written to handle event is present, but what i am trying to handle is 2 different events. How can i achieve this?

Snapshot of surface with 2 rects, when i click on both rects, i get '2' in my alert.

Snapshot of surface with 2 rects, when i click on both rects, i get '2' in my alert.

Was it helpful?

Solution

JavaScript has functional scope, not block scope, so you only have one ii variable, which is always equal to "2" by the time you click on a rect. There are many ways to fix this, example below :

function renderICD() {
    var totalx=1200;
    var totaly=1000;
    var xOffset = 150;
    var yOffset = 20;

    surface = dojox.gfx.createSurface("icdTab",totalx+2,totaly+2);
    var grid = surface.createGroup();
    var step = 1;
    var xyHolder = {};
    var group = grid.createGroup();

    dojo.forEach([0,1], function(item, ii) {
         var x = (step-1) * (75+85);
         step++;

         var group = grid.createGroup();

         group.createRect({x:xOffset+x+33, y:yOffset+20+90, width: 10, height: 10}).setFill([255, 255, 255, 0.9])
            .setStroke({color:'black' , width:2});


              dojo.connect(group.getEventSource(),"onclick",function(e) {
                       var internal = ii;
                       alert("publishing "+internal);
               //shape was clicked, now do something!
                        });

         grid.createText({x:xOffset+x+33, y:yOffset+20+80, text:ii,align:"middle"})
            .setFill('red')
            .setFont({size: '10px',weight: "bold"});
    });
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top