Search code examples
ractivejs

Dynamic variable name binding


I have a problem similar to this one. But in my case a have dynamic amount of objects (posts) to bind so if I do it this way:

{{#each Posts}}
...
  {{#each Comments}}
  {{/each}}
  <form> /* new comment is added here */
    <textarea name="text" value="{{newCommentText}}" />
    <input type="submit" disabled="{{!newCommentText}}" />
  </form>
{{/each}}

the values of all textareas are synchronized. What I need is to somehow specify a unique variable name for each form (i. e. {{PostId_newCommentText}}). Is there a way to achieve that?


Solution

  • You can use restricted references to add each new comment to the corresponding Post:

    {{#each Posts}}
        <form>
            <!-- .newCommentText === this.newCommentText -->
            <textarea name="text" value="{{.newCommentText}}" />
            <input type="submit" disabled="{{!.newCommentText}}" />
        </form>
    {{/each}}
    

    Another option is to use @index and store all new comments in separate array:

    {{#each Posts}}
        <form>
            <textarea name="text" value="{{NewComments[@index]}}" />
            <input type="submit" disabled="{{!NewComments[@index]}}" />
        </form>
    {{/each}}
    

    Live demo here.