0

I'm using a loop to push a number of views to an array. Attached to each view is a modifier and a surface.

var surfaces = [];

for(var i = 0; i<8; i++) {

    var gridSurfaceView = new View();

    var gridSurface = new Surface({
        size: [25, 25],
        content: "hello" + i,
    })

    var gridSurfaceMod = new Modifier({
        origin: [0.5,0.5],
        align: [0.5,0.5]
    })

    gridSurfaceView.add(gridSurfaceMod).add(gridSurface);

    surfaces.push(gridSurfaceView);
}

I want to access the content of the surfaces within the surfaces array. I was hoping that this would happen:

 surfaces[0].getContent() //returns hello0
 surfaces[1].getContent() //returns hello1

But of course it won't, because each cell in surfaces is a view, not a surface.

Is there anyway to access these surfaces from this array?

Sam Seidenberg
  • 153
  • 1
  • 7

1 Answers1

1

I usually do some quick manual binding for organization and to be able to access related objects. You could for instance initialize the View, then bind the surface and modifier to the view before adding them.

This is how you could change the code..

var surfaces = [];

for (var i = 0; i<8; i++) {

    var gridSurfaceView = new View();

    gridSurfaceView.surface = new Surface({
        size: [25, 25],
        content: "hello" + i,
    });

    gridSurfaceView.mod = new Modifier({
        origin: [0.5,0.5],
        align: [0.5,0.5]
    });

    gridSurfaceView.add(gridSurfaceView.mod).add(gridSurfaceView.surface);

    surfaces.push(gridSurfaceView);
}

Then you can do..

surfaces[0].surface.getContent() //returns hello0
surfaces[1].surface.getContent() //returns hello1

Hope this helps!

EDIT:

Alternatively, to get the same interface you could define a getContent function on your view and then bind the surface to that function.

var gridSurfaceView = new View();

var gridSurface = new Surface({
    size: [25, 25],
    content: "hello" + i,
})

gridSurfaceView.getContent = function(){
    return this.getContent()
}.bind(gridSurface);

Then your code should work as follows..

surfaces[0].getContent() //returns hello0
surfaces[1].getContent() //returns hello1
johntraver
  • 3,612
  • 18
  • 17