Thursday, December 17, 2015

Aurelia - A use case for view-model.ref

A couple of days ago I blogged on how to get access to the view model of a custom element. When I wrote it, my use case was calling a method of the view model from the containing component. As happens so often, once I had done this, another use case came up. I think this one is sufficiently interesting to warrant another post.

I have two independent components. One displays the current version of a banner image, and the other is the styled file picker that I use to select a file. What I want is for the component that shows the current banner image to display an indicator when the user has selected a new image but hasn't saved it, since I cannot show the new image on the web page until they actually upload it.

What I don't want to do is add a property to the view model of the page. The page itself doesn't care about this interaction and doesn't need to do anything to mediate it. It is an accidental participant in the process, and so adding a property just to allow the two components to interact seems ugly. Fortunately, I don't have to. The file upload component already has a property hasFileSelected, and the display component needs a property imageChanged, so I can just write the following in the HTML:

    <banner-image src.bind="bannerImageUrl" image-changed.bind="filePicker.hasFileSelected"></banner-image>
    <file-picker url.bind="ui.bannerImageUrl" view-model.ref="filePicker"></file-picker>

Notice how the banner-image component binds the image-changed property to the file-picker's hasFileSelected using the ref. Simple. Everything is done in the view, where it makes the most sense.

This is one of the things that I am loving about Aurelia, the ability to leverage on HTML when it makes sense. Sometimes, the complexity of a javascript view model is more than you need, and with Aurelia, you don't need it.

No comments: