v0.2.0 - `setup` and store simplification
Release Notes for v0.2.0 - setup and store simplification
In this release, we've made significant changes to the ReactiveElement
class and the store
function to simplify their usage and make them more intuitive. Here are the key changes:
Changes to ReactiveElement
-
The
define
method has been renamed tosetup
to better reflect its purpose. This method is used to set up observables, computed properties, and attributes for the element. -
The
subscribe
method has been renamed toconnect
to better reflect its purpose. This method is used to connect an observable from a store to the element.
Changes to store
- The
store
function now supports actions as part of the initial state. If a function is provided in the initial state, it will be registered as an action.
Examples
Here are some examples of how to use the new features:
Counter Component
<script type="module">
const { html, ReactiveElement } = cami;
class CounterElement extends ReactiveElement {
count = 0
constructor() {
super();
this.setup({
observables: ['count']
})
}
template() {
return html`
<button @click=${() => this.count--}>-</button>
<button @click=${() => this.count++}>+</button>
<div>Count: ${this.count}</div>
`;
}
}
customElements.define('counter-component', CounterElement);
</script>
Todo List Component (uses store)
<script type="module">
const { html, ReactiveElement } = cami;
const TodoStore = cami.store({
todos: [],
add: (store, todo) => {
store.todos.push(todo);
},
delete: (store, todo) => {
const index = store.todos.indexOf(todo);
if (index > -1) {
store.todos.splice(index, 1);
}
}
});
TodoStore.use((context) => {
console.log(`Action ${context.action} was dispatched with payload:`, context.payload);
});
class TodoListElement extends ReactiveElement {
todos = this.connect(TodoStore, 'todos');
constructor() {
super();
this.setup({
observables: ['todos']
})
}
template() {
return html`
<input id="newTodo" type="text" />
<button @click=${() => {
const newTodo = document.getElementById('newTodo').value;
TodoStore.add(newTodo);
document.getElementById('newTodo').value = '';
}}>Add</button>
<ul>
${this.todos.map(todo => html`
<li>
${todo}
<button @click=${() => TodoStore.delete(todo)}>Delete</button>
</li>
`)}
</ul>
`;
}
}
customElements.define('todo-list-component', TodoListElement);
</script>