Cédric
Cédric

Reputation: 419

Polymer array as member in element

I'm trying to acces a variable in an array as a member of a polymer-element. But I keep getting "Cannot read property NaN of undefined". This is my code, I get the error at this.images[this.x]:

<link rel="import" href="bower_components/polymer/polymer.html">

<polymer-element name="big-picture" noscript>

<template>
    <style>
    #crop
    {
        display: block;
        position: relative;
    }
    #mainpictop
    {
        position: absolute;
        width: 100%;
    }
    #mainpicbottom
    {
        position: absolute;
        width: 100%;
    }
    </style>

    <div id="crop">
        <img id="mainpictop" src={{pic1source}} style="opacity:{{pic1opacity}}"></img>
        <img id="mainpicbottom" src={{pic2source}} style="opacity:{{pic2opacity}}"></img>
    </div>


</template>
<script>
    Polymer('big-picture',{
        x:1,
        currentTop:0,
        currentBottom:1,
        numpics:5,
        transitionspeed:200,
        images: new Array,
        pic1opacity: 1,
        pic2opacity:1,
        pic1source: "img/main/1.jpg",
        pic2source: "img/main/2.jpg",
        ready: function(){


            for (i=0;i<this.numpics;i++)
            {
                this.images[i]="img/main/".concat(i+1).concat(".jpg");
            }

            setInterval(function() {
                changeImageSrc()
          },this.transitionspeed);
        }
    });
    function changeImageSrc() {

    if(this.pic1opacity==1)
    {
        this.pic1opacity=0;
        this.pic2opacity=1;
        if (this.currentTop!=this.currentBottom)  
            this.pic2source = this.images[this.x];
        else
        {
            this.x=this.x+1;
            if(this.x===this.numpics)
                this.x=0;
            this.pic2source = this.images[this.x];
        }
        this.currentBottom=this.x;
    }
    else
    {
        this.pic2opacity=0;
        this.pic1opacity=1;
        if (this.currentTop!=this.currentBottom)  
            this.pic1source = this.images[this.x];
        else
        {
            this.x=this.x+1;
            if(this.x===this.numpics)
                this.x=0;
            this.pic1source = this.images[this.x];
        }
        this.currentTop=this.x;

    }



  this.x=this.x+1;
  if(this.x===this.numpics)
    this.x=0;
}

</script>
</polymer-element>

I've only just began to learn Polymer so don't be too harsh please.

Upvotes: 1

Views: 188

Answers (1)

adam8810
adam8810

Reputation: 731

This is a scope issue. Be very careful when using "this" within other functions because the context of "this" changes to the function it is in. In your case the "this" variable has been set to changeImageSrc()'s context.

An easy fix is to store a reference to "this" in another variable (var _this = this;) and use that new variable when you need to take actions upon your Polymer variables.

Upvotes: 1

Related Questions