Au 2.0: Template refs with repeat.for

Hello,

I’ve searched the documentation, and Discourse, and I can’t seem to find a definitive approach to template refs with a repeat.for.

A number of Discourse posts sort of swirl around the issue, but none seems to be working for me. I’ve hit upon this, below, but I don’t know if it’s acceptable:

...
<div repeat.for="doc of docs" ref="listOfDocs[$index]"></div>
...

In the view model, I get an object, not an array, that has the structure:

{
   0: (a doc HTMLElement),
   1: (a doc HTMLElement),
   2: (a doc HTMLElement),
   ...
}

where each key is the index. I have a computed property that makes this object practical:

...
get $docElements() {
  return Object.values(this.listOfDocs);
}
...

where listOfDocs is properly on the view model, as I would expect.

All of this works, and the computed property does, indeed, recompute. I just want to be sure that this approach is sound.

I’d probably do the same thing :slight_smile: , though you may end up with some null value in the array when the repeater collection shrinks.

Yeah, I figured out the null problem, funny you should say :slightly_smiling_face: . But it’s easy to defend against. Moving to a dynamic filter seemed to cause the null s to go away, though.

Is this a viable feature? What if we simply had this:

...
<div repeat.for="doc of docs" ref="listOfDocs"></div>
...

with no $index reference. Aurelia could automatically populate an array based on $index since it’s on a repeat.for. (Perhaps similar logic as what we have with @children).

This only works if your setter does some array appending behind the scene. It wouldn’t be able to clear up the reference later though, since the value you get back to compare to decide whether the reference should be cleared isn’t the same, due to the lack of index information.

Personally I would also prefer something plain and clear on the template.

1 Like