Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.bind vs string interpolation in aurelia

Tags:

aurelia

In our code base we have a mixture of the following:

  1. attribute="${something}", attribute="${something | converter}", etc.
  2. attribute.bind="something", attribute.bind="something | converter"

I find the latter easier to read.

The examples I'm referring to are exactly like the above; i.e., they do not add any additional string content.

I think that it's easier on Aurelia too. Am I correct?

Also, for these specific cases where no actual interpolation is involved, is there any benefit to the first form? (other than it is two characters less to type.)

like image 528
Dave Avatar asked Oct 18 '22 17:10

Dave


1 Answers

Given the examples you have shown, I would recommend using option 2. It really isn't "easier on Aurelia," but it is more explicit that you are binding the value of that attribute to the property listed.

Original Answer Below

The benefit of the first option is when you have, for example, an attribute that accepts many values but as a single string. The most common example of this is the class attribute. The class attribute accepts multiple classes in a space-separated list:

<div class="foo bar baz"></div>

Imagine we only want to add or remove the class baz from this list based on a prop on our VM someProp while leaving the other classes. To do this using the .bind syntax, we would have to create a property on our VM that has the full list but adds or removes baz as determined by the value of someProp. But using the string interpolated binding, this becomes much simpler:

 <div class="foo bar ${someProp ? 'baz' : ''}"></div>

You can imagine how this could be extended with multiple classes being added or removed. You could maybe create a value converter to do this using the .bind syntax, but it might end up with something that wasn't as readable.

I could imagine a value converter being created that might look something like this in use:

 <div class.bind="someProp | toggleClass:'baz':'foo':bar'"></div>

I really think this is much less readable than using the string interpolation syntax.

By the way, the value converter I imagined above would look like this:

export class ToggleClassValueConverter {
  toView(value, toggledClass, ...otherProps) {
    return `${otherProps.join(' ')} ${value ? toggledClass : ''}`;
  }
}

The best part is that I'm still using string interpolation in the value converter :-)

like image 88
Ashley Grant Avatar answered Oct 21 '22 00:10

Ashley Grant