ES6+ Features Essenziali
Destructuring
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// Object destructuring
const {name, email} = user;
// Con Livewire
Alpine.data('userForm', () => ({
user: {},
init() {
const {name, email} = this.user;
}
}));
Arrow Functions
// Tradizionale
posts.map(function(post) {
return post.title;
});
// Arrow function
posts.map(post => post.title);
// Con Alpine.js
<div x-data="{ posts: [] }">
<template x-for="post in posts.filter(p => p.published)">
<div x-text="post.title"></div>
</template>
</div>
Async/Await
// Promise
fetch('/api/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/Await (più pulito)
async function fetchPosts() {
try {
const response = await fetch('/api/posts');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}