how to use the ref.view-model feature

5.3k views Asked by At

I'm seeing this feature in the docs, but I can't quite figure out how to use it from that information.

It says: <i-produce-a-value ref.view-model="producer"></i-produce-a-value> <i-consume-a-value input.bind="producer.output"></i-consume-a-value> What does this look like in real world example?

2

There are 2 answers

5
Ashley Grant On BEST ANSWER

This syntax has actually changed to be more consistent with the rest of Aurelia's binding syntax in our latest release (which hit after you posted this question).

The syntax is now:

<i-produce-a-value view-model.ref="producer"></i-produce-a-value>
<i-consume-a-value input.bind="producer.output"></i-consume-a-value>

But anyways, view-model.ref="producer" creates an alias to the view-model for the i-produce-a-value custom element which you can then use elsewhere to pass to another custom element or use properties of the VM. Thus in the second line of the code above, i-consume-a-value has a property called input that has been bound to the output property of the VM of the i-produce-a-value element.

Let's look at an example. Say you have a DatePicker custom element. Its view model has several properties such as dayOfWeek and month. You would like to use the properties in other elements on your view. You could bind a property on your View's VM to each of these properties and then bind to your View's properties elsewhere in your view where you want to use these values, or you can use the view-model.ref to allow you to bind directly to these values on your DatePicker custom element. Something like this:

<date-picker value.bind="eventDate" 
             view-model.ref="eventDateVM"></date-picker>
<div>
  <p>Event Month: ${eventDateVM.month}</p>
  <p>Event Day of Week: ${eventDateVM.dayOfWeek}</p>
  <img src.bind="eventDateVM.dayInHistoryImageUrl" />
</div>

So, in this example, we have bound the value property of the DatePicker to the eventDate property of our page's VM. More importantly, we have created an alias to the VM of the DatePicker custom element and named it eventDateVM. We then use this alias to display the month and day of week for the date picked in the custom element. This imaginary DatePicker also has a VM property that is set to the url for a picture of something that happened on the date chosen, so we bind that url to the src property of an img tag.

Let me know if you have any more questions about this very powerful feature of Aurelia!

0
DaniCE On

Just an update: in Aurelia 2 the syntax has changed to

<i-produce-a-value component.ref="producer"></i-produce-a-value>