Search code examples
javascriptdompolymer

Polymer observable object in dom-repeat not getting update


I'm trying to display an object that contains array in a dom-repeat. The data structure is as following: answerObject: {firstQuestion: ["one", "two"], secondQuestion: ["three", "four"]}

I'm using computed binding in a nested dom-repeat to convert the object to array, and then use another dom-repeat to display content of the array.

  <ul>
    <template is="dom-repeat" items="[[_makeArray(answerObject)]]" as="question">
      <li>[[question.key]]</li>

      <ul>
          <template is="dom-repeat" items="[[question.listOfAnswer]]" as="answer">
              <li>[[answer]]</li>
          </template>
      </ul>
 </template>

I created the answerObject property as following:

  answerObject: {    
     type: Object,
     notify: true,
     value: {firstQuestion: ["one", "two", "three"], 
             secondQuestion: ["four","five"] },
     observer: '_answerChanged'   
  },

I tried all different ways to observe the object or the array, and none triggers the function '_answerChanged' nor '_makeArray'.

   /* mutating object and then notifyPath */
   this.set('answerObject.firstQuestion', ["newone"]);
   this.notifyPath('answerObject.firstQuestion');

   /* mutating array then notifySplices */
   this.push('answerObject.secondQuestion',"six");
   this.notifySplices('answerObject.secondQuestion', [
     {index:3, removed: [], addedCount: 1, object: _this.answerObject.secondQuestion, type:'splice'}
   ]);

   /* dirty check */
   var array = this.answerObject.firstQuestion;
   this.answerObject.firstQuestion=[];
   this.answerObject.firstQuestion = array;

Any suggestion what do I miss? Thank you.


Solution

  • Observer is not triggered, because your scenario is not supported.

    As per official documentation:

    Primitive array items are not supported. This is because primitives (like number, string and boolean values) with the same value are represented by the same object.

    The currently recommended workaround (also stated in my previous link) is, that you simply wrap your primitive values with a simple object.

    So, instead of this:

    ["one", "two", "three"]
    

    You use something like this:

    [{ value: "one" }, { value: "two" }, { value: "three" }]