0

Im really new in Famo.us and JavaScript. Based on the Timbre Example im trying to implement a GridLayout on the PageView. That works fine. Now i planed to do a click event on every ImageSurface. But that doesnt work like that. Here's my code:

for(var i = 0; i < this.options.imageData.length; i++) {

        this.imageSurfaces.push(new ImageSurface({
            content: this.options.imageData[i].imgUrl,
            size: [200, 200],
            properties: {
               // backgroundImage: this.options.imageData[i].imgUrl,
                color: "black",
                textAlign: 'center'
            }
        }));
        //console.log(i);

        this.imageSurfaces[ii].on('click', function (){
            console.log("Test Click - " + ii + " - " + i);
            console.log(this.imageSurfaces[ii]);
        }.bind(this));
Ced
  • 1

2 Answers2

0

I'm missing where ii is defined.

However, if you store the surface in a temporary var, you'll be able to hook up handlers (and do other stuff) with it:

var aSurface, i;
//
for(i = 0; i < this.options.imageData.length; i++) {
      aSurface = new ImageSurface({
           content: this.options.imageData[i].imgUrl,
           size: [200, 200],
           properties: {
                // backgroundImage: this.options.imageData[i].imgUrl,
                color: "black",
                textAlign: 'center'
            }
        });
     aSurface.('click', function (){
        console.log("Test Click" + i);
        console.log(aSurface);
    }.bind(this));
})
brennanyoung
  • 6,243
  • 3
  • 26
  • 44
0

You'll want to encapsulate the event handler in a closure, otherwise all of your surfaces will end up with the same click event.

for (var i = 0; i < this.options.imageData.length; i++) {
    aSurface = new ImageSurface({
        content: this.options.imageData[i].imgUrl,
        size: [200, 200],
        properties: {
            //whatever properties you want
        }
    });
    (function (aSurface) {
        aSurface.on('click', function () {
            console.log(aSurface.options.imageData.imgUrl);
        });
    }(aSurface);
}
Tj Gienger
  • 1,395
  • 1
  • 12
  • 17