Complex features with interactive code demonstrations
// Define a Todo component
class TodoComponent extends MicroUI.Component {
constructor(element, options) {
super(element, options);
this.todos = options.todos || [];
}
template() {
return `
<div class="todo-app">
<input type="text" class="todo-input"
placeholder="Add new todo...">
<button class="btn add-todo">Add</button>
<div class="todo-list"></div>
</div>
`;
}
onMount() {
this.renderTodos();
this.bindEvents();
}
addTodo(text) {
this.todos.push({
id: Date.now(),
text,
completed: false
});
this.renderTodos();
}
}
// Create delegation namespace
const myNamespace = new MicroUI.DelegationNamespace();
// Add middleware for logging
myNamespace.addMiddleware('click', function(event, next) {
console.log('Click intercepted:', event.target);
next();
});
// Delegate events with namespace
myNamespace.delegate('click', '.delegate-item',
function(event) {
this.classList.toggle('clicked');
}
);
// Dynamic content - events still work!
const newItem = document.createElement('div');
newItem.className = 'delegate-item';
newItem.textContent = 'Dynamic item';
container.appendChild(newItem);
// AJAX with loading states and error handling
function loadUserData(userId) {
const loadingEl = MicroUI.$('.loading');
const resultEl = MicroUI.$('.result');
// Show loading state
MicroUI.html(loadingEl, 'Loading user data...');
MicroUI.fadeIn(loadingEl, 200);
return MicroUI.get(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(function(user) {
MicroUI.fadeOut(loadingEl, 200);
MicroUI.html(resultEl, `
<h4>${user.name}</h4>
<p>Email: ${user.email}</p>
<p>Company: ${user.company.name}</p>
`);
MicroUI.fadeIn(resultEl, 300);
})
.catch(function(error) {
MicroUI.fadeOut(loadingEl, 200);
MicroUI.html(resultEl, `❌ Error: ${error.message}`);
MicroUI.fadeIn(resultEl, 300);
});
}
// Form validation with MicroUI
function validateForm(formElement) {
const inputs = MicroUI.$$('input[required]', formElement);
let isValid = true;
inputs.forEach(function(input) {
const value = input.value.trim();
const errorEl = MicroUI.$(`.error-${input.name}`);
if (!value) {
MicroUI.addClass(input, 'error');
MicroUI.html(errorEl, 'This field is required');
MicroUI.fadeIn(errorEl, 200);
isValid = false;
} else {
MicroUI.removeClass(input, 'error');
MicroUI.fadeOut(errorEl, 200);
}
});
return isValid;
}
// Handle form submission
MicroUI.on('submit', '#demo-form', function(e) {
e.preventDefault();
if (validateForm(this)) {
// Process form data
MicroUI.post('/api/contact', new FormData(this));
}
});