aureliaaurelia-templating

scope based ref in Aurelia


I have ref for form which is a custom element

<form ref="domRef" ...>

I have ref for field too, which is another custom element(being used inside the form)

<input type="text" ref="domRef" .....>

but inside attach() of form's view model I am getting this.domRef is input's reference.

attached(){        
     console.log(this.domRef);
}

So, as the execution goes on domRef is being overridden by the latest one. Why?

Why domRef's are not different for different scopes?

I cannot use different name for ref as all are being generated dynamically. Please help me on this if there is any alternative.

Update After Ashley's Answer:

Custom Element Form has its own VM and Custom Element Field has its own VM too.

Views:

    <template>
        <form ref="domRef">
                <compose view-model="resources/elements/field" ..... containerLess>
                </compose>
        </form>
    </template>
    <template>
        <input type="text" ref="domRef"></input>
    </template>

View-Models:

    export class Form{
     ..
     attached(){
      console.log(this.domRef); //returns Input's Ref Which is not correct
     }
    }
    export class Field{
     ..
     attached(){
      console.log(this.domRef); //returns Input's Ref Which is correct
     }
    }

Then if domRef belongs to the current VM why is it happening?


Solution

  • After digging out everything, I got the solution. i.e initializing the domRef at the time of constructing.

        export class Form{
         constructor(){
           this.domRef = null;
         }
         attached(){
          console.log(this.domRef); //returns Form's Ref Which is correct
         }
        }
        export class Field{
         constructor(){
           this.domRef = null;
         }
         attached(){
          console.log(this.domRef); //returns Input's Ref Which is correct
         }
        }
    

    Strange but Worked.