Ractive.js is a template-driven UI library that brings two-way data binding, transitions, and reactive calculations to the DOM.
Initialization
const ractive = new Ractive({
target: '#app',
template: '#my-template',
data: {
greeting: 'Hello',
user: { name: 'Alice' },
count: 0
}
});
Template Syntax (Mustache)
<!-- Data output -->
<h1>{{greeting}}, {{user.name}}!</h1>
<!-- Raw HTML output -->
<div>{{{unescapedHtml}}}</div>
<!-- Two-way input binding -->
<input value="{{user.name}}" />
<!-- Conditionals -->
{{#if count > 0}}
<p>Items in cart: {{count}}</p>
{{else}}
<p>Your cart is empty.</p>
{{/if}}
<!-- List iteration -->
<ul>
{{#each items:i}}
<li>{{i + 1}}: {{this.name}}</li>
{{/each}}
</ul>
Instance Methods
// Reading and writing reactive data
ractive.get('user.name'); // => "Alice"
ractive.set('user.name', 'Bob'); // Updates DOM immediately
// Number helpers
ractive.add('count', 1);
ractive.subtract('count', 1);
// Toggle boolean value
ractive.toggle('isVisible');
// Observe changes
ractive.observe('user.name', (newValue, oldValue) => {
console.log(`Name changed to ${newValue}`);
});
Event Handling
<button on-click="@this.fire('submitForm', user)">Submit</button>
ractive.on('submitForm', (event, user) => {
console.log('Submitted user:', user);
});