javascriptdata-bindingjavascript-objectspolymer-1.0polymerfire

Data binding to a dynamic path in Polymer


I am building a web app with Polymer 1.0 and Firebase, and I want to have the view change when data was entered into a path with a user ID in the path. To do that, I want to do something like this:

[[question.answers.(user.uid).choice]]

Let me explain in more detail. So, in the template, I have something like this:

 <ul id="question-list">
    <template is="dom-repeat" items="[[questions]]" sort="_computeSort" as="question">
      <li class="card question" data-key="[[question.$key]]" question="[[question]]">
        <h3 class="content">[[question.question]]</h3>
        <p hidden$="[[ MY DATA BINDING HERE ]]">[[question.afterMessage]]</p>
      </li>
    </template>
  </ul>

If you look at the <p> element above, inside the hidden attribute is where I want to have my data binding to happen. The structure of a questions path is like this:

questions data structure

So questions is a collection of questions, and each question has a property afterMessage, which I want to show the user after answering the question.

In order to check if the user has answered the question, I have a path called answers within the questions path. Inside that answers path, I have the users's key as a key to the choice that the user chose.

So, if a user with user key of ZjHDMDa270Uyp6sAL02Mam2ftGf2 is logged into my app, the data binding path to that user's answer would be:

[[quesion.answers.ZjHDMDa270Uyp6sAL02Mam2ftGf2.choice]]

Now this above expression is what I want to bind to, but of course the user ID changes from user to user, so how can I do this? In other words, I want to do something like this:

[[question.answers.(user.uid).choice]]

Solution

  • Polymer data bindings don't support nesting or expressions. You would likely have to use a computed binding like this:

    // template's computed binding
    [[_getChoice(question, user.uid)]]
    
    // script
    Polymer({
      _getChoice: function(question, uid) {
        return question.answers[uid].choice;
      },
      ...
    });