In Aurelia 2, lambda expressions bring a breath of fresh air to templating by enabling developers to write concise and expressive code directly within templates. A significant advantage of lambda expressions is that they allow developers to perform various operations without needing value converters, leading to cleaner and more maintainable code.
This article explores lambda expressions in Aurelia 2, emphasising filtering, sorting, and other operations that can be performed without value converters.
Filtering Without Value Converters
In Aurelia, lambda expressions provide a more straightforward approach to filtering items within templates, removing the need for value converters.
Before Lambda Expressions:
Previously, to filter some array items, you would have used a value converter like this:
With Lambda Expressions:
Now, you can achieve the same thing without writing any additional code:
The lambda expression calls a callback function isGood
defined inside the template to determine if the item should be filtered. It is worth noting that sometimes you will still want a value converter from a testing perspective, but in most cases, a lambda expression can save the boilerplate.
Combining Filtering and Sorting
Lambda expressions allow you to chain multiple array methods, making it easy to combine filtering and sorting. Here’s an example:
${item.name}
Event Handling Made Simple
With lambda expressions, you can write event handling in a more JavaScript-like way. For example:
Mapping and Reducing Within Templates
You can map and reduce arrays directly within your templates, reducing the need for value converters.
Mapping:
Displaying an array of keywords as a comma-separated list:
${keywords.map(x => x.name).join(', ')}
Reducing:
Calculating the total of items in a cart:
Total: ${items.reduce((sum, product) => sum + product.price, 0)}
Conclusion: The Power of Lambda Expressions
Lambda expressions in Aurelia 2 offer a modern and efficient way to write various logic within templates. By supporting a subset of JavaScript’s Arrow Function syntax, they align closely with conventional JavaScript, making your Aurelia code more readable and maintainable.
The ability to replace value converters with lambda expressions for common tasks like filtering is a game-changer. It allows developers to write cleaner code without additional artefacts, such as value converters.
Embracing lambda expressions in your Aurelia projects will enable you to write more elegant code and tap into a more JavaScript-like way of handling templating. The examples showcase lambda expressions’ versatility and power, from filtering and sorting to mapping and reducing.
Explore, experiment, and enjoy the benefits of lambda expressions in Aurelia 2, and take your front-end development to the next level. You can read more about lambda expressions in the official docs here.