Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Polymer push method in a object

I'm a beginner to javascript and Polymer: i need to use native polymer push method in my custom object, but the browser it gives me back:

"Uncaught TypeError: Cannot read property 'length' of undefined"

This is a simplyfied version of my code:

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

<dom-module id='random-tag'>
  <template>
    <template is='dom-repeat' items='[[MyObject.getArray()]]'>
      <div>
        <h2>[[item.id]]</h2>
      </div>
    </template>
  </template>

  <script>
    Polymer({
      is: 'random-tag',

      properties: {
        MyObject: {
          type: Object
        }
      },

      MyObject2: function(){
        var myArray = [];
        var idMap = {};

        this.getArray = function(){
          return this.myArray
        };

        this.add = function(element){
          //The problem is here: probably Polymer don't see 'myArray'
          //in MyObject2 because the path is wrong
          Polymer.Base.push('myArray', element)
          idMap[element.id] = myArray.length
        };

        this.getIndex = function(id){
          return idMap[id]
        }
      },

      ready: function(){
        this.MyObject = new this.MyObject2()
        this.MyObject.add({id : 'thing1'})
        console.log('thing1 has index: ' + this.MyObject.getIndex('thing1'))
      }
    });
  </script>
</dom-module>
like image 652
James Coccinella Avatar asked Dec 05 '25 07:12

James Coccinella


1 Answers

You need to start from a Polymer element like

<script>
    Polymer({
      is: 'random-tag',

      properties: {
        MyObject: {
          type: Object
        }
      },

      var self = this;

      MyObject2: function(){
        var myArray = [];
        var idMap = {};

        this.getArray = function(){
          return this.myArray
        };

        this.add = function(element){
          //The problem is here: probably Polymer don't see 'myArray'
          //in MyObject2 because the path is wrong
          self.push('myArray', element)
          idMap[element.id] = myArray.length
        };

        this.getIndex = function(id){
          return idMap[id]
        }
      },

      ready: function(){
        this.MyObject = new this.MyObject2()
        this.MyObject.add({id : 'thing1'})
        console.log('thing1 has index: ' + this.MyObject.getIndex('thing1'))
      }
    });
  </script>
</dom-module>

not tested (I don't know JS too well so use with caution)

like image 90
Günter Zöchbauer Avatar answered Dec 07 '25 19:12

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!