Skip to content
conversejsPublic

About

Models and Collections for modern web apps

Topics

Resources

Stars

16 stars

Watchers

1 watching

Forks

Repository files navigation

Skeletor

Skeletor

XMPP Chat CI Tests

Skeletor is a lightweight, TypeScript-first reactive data library.

It lets you define typed models and react to changes with events or subscriptions, while persisting to IndexedDB, localStorage, sessionStorage, memory, SQLite (Node) or a REST API.

Skeletor is a modernized rewrite of Backbone's Models and Collections, without jQuery, without Underscore, and without Views or Routing. If you know Backbone, everything transfers directly. If you don't, there's nothing to unlearn.

Skeletor powers Converse.js, a full-featured open-source XMPP chat client.

Why Skeletor?

  • Reactive models — set an attribute, get a change event. Subscribe with a callback and an unsubscribe function. Works with any UI layer.
  • Direct attribute access — model.attrs.name = 'Bob' fires change events, no boilerplate needed.
  • Computed properties — declare derived values with explicit dependencies; they cache, recalculate, and fire change events automatically.
  • Indexed lookups: Backbone can only look a model up without a scan by its id. Skeletor collections can declare indexes on any attribute, computed property or function, so getBy, getAllBy, where and findWhere stay fast as collections grow.
  • Signals bridge: read attributes and collections as TC39 Signals, so renderers such as Lit update only the bindings whose values changed.
  • Store-style subscriptions — subscribe() returns an unsubscribe function, compatible with React's useSyncExternalStore and similar APIs.
  • Built-in persistence — IndexedDB, localStorage, sessionStorage, SQLite (Node), and REST out of the box.
  • TypeScript-first — full type definitions, generic model attributes, typed computed properties.
  • No jQuery, no Underscore — native browser APIs and lodash-es with individual imports for tree-shaking.
  • Works anywhere — browser, Node.js (22+), Web Workers. ESM and UMD builds included.
  • Backbone-compatible — get, set, events, collections: all there. Largely API-compatible with Backbone's data layer (see Coming from Backbone for the differences).

When to use it

  • You're modernizing a Backbone-era app and want a typed, promise-capable data layer without a rewrite.
  • You want a headless store with built-in persistence that binds to any UI framework.
  • You render with signals (for example Lit) and want domain models whose attributes and collections read as signals.
  • Your state is genuinely domain data — entities with identity, relationships, and a persisted lifecycle.

When to reach for something else

  • Your "state" is mostly ephemeral view state (form inputs, toggles, hover). Keep that in your view layer, or in plain signals: Skeletor's value is in models with identity and persistence, which such state doesn't need.
  • You need time-travel, structural sharing, or a strict immutable single-store architecture — that's Redux's territory.

Installation

npm install @converse/skeletor

Quick Start

Define a model with typed attributes, listen for a change, then make one:

import { Model } from '@converse/skeletor';

interface TodoAttrs {
  title: string;
  done: boolean;
}

class Todo extends Model<TodoAttrs> {
  get defaults() {
    return { title: '', done: false };
  }
}

const todo = new Todo({ title: 'Write the docs' });

todo.on('change:done', (model, done) => {
  console.log(`"${model.get('title')}" done: ${done}`);
});

todo.attrs.done = true; // logs: "Write the docs" done: true

That's the core loop: models hold attributes, writes fire events, and your UI reacts. The sections below cover computed properties, collections, persistence, and binding to UI libraries.

Usage

API at a glance

Export What it provides
Model get/set, attrs proxy, computed properties, change tracking, validation, server sync
Collection Full array API plus where, findWhere, pluck, groupBy, keyBy, countBy, sortBy, indexed getBy/getAllBy
EventEmitter on/off/trigger/once, listenTo/stopListening, subscribe() returning an unsubscribe function
PersistentStorage IndexedDB, localStorage, sessionStorage, SQLite (Node), and in-memory backends. autoSync for transparent auto-save and auto-hydrate.
createSignals attrSignal and collectionSignal: read models and collections through TC39 Signals, with the Signal you pass in
sync Low-level Fetch-based HTTP function (override for custom transports)

Models

import { Model } from '@converse/skeletor';

interface UserAttrs {
  firstName: string;
  lastName: string;
  active: boolean;
}

class User extends Model<UserAttrs> {
  get defaults() {
    return { firstName: '', lastName: '', active: false };
  }

  get computed() {
    return {
      fullName: {
        deps: ['firstName', 'lastName'],
        fn: (model: User) => `${model.get('firstName')} ${model.get('lastName')}`,
      },
    };
  }
}

const user = new User({ firstName: 'Alice', lastName: 'Smith' });

// Read an attribute with get() or through the attrs proxy
user.get('firstName'); // → 'Alice'
user.attrs.firstName; // → 'Alice'

// Computed values are read the same way (cached, never persisted)
user.get('fullName'); // → 'Alice Smith'

// React to changes
user.on('change:fullName', (model, value) => {
  console.log('Name is now', value);
});

// Store-style subscription (returns an unsubscribe function)
const unsub = user.subscribe((model, changed) => {
  console.log('Changed attrs:', changed);
});

// Write: both forms fire change events
user.attrs.firstName = 'Bob'; // fires 'change:firstName' and 'change:fullName'
user.set('active', true); // fires 'change:active'

unsub(); // clean up

Collections

import { Model, Collection } from '@converse/skeletor';

interface UserAttrs {
  id: number;
  name: string;
  active: boolean;
}

class User extends Model<UserAttrs> {}

class Users extends Collection<User> {
  get model() {
    return User;
  }
  get url() {
    return '/api/users';
  }
}

const users = new Users([
  { id: 1, name: 'Alice', active: true },
  { id: 2, name: 'Bob', active: false },
]);

users.add({ id: 3, name: 'Carol', active: true });

const active = users.filter((u) => u.get('active'));
const names = users.pluck('name'); // → ['Alice', 'Bob', 'Carol']

// Subscribe to structural changes (fires once per operation, not per model)
const unsub = users.subscribe((collection) => {
  console.log('collection changed, length:', collection.length);
});

// Load from the server at `url`
await users.fetch();

By default fetch() updates the collection in place with set(): it adds new models, merges changes into existing ones, and removes models missing from the response. Pass { reset: true } to replace the contents wholesale instead.

Indexes

In Backbone, collection.get() finds a model by its id in O(1) time. Any other lookup (findWhere, where, find) walks the whole collection, in O(n) time.

In Skeletor you can now find models in O(1) time through other keys as well, if you declare them as indexes.

An index can be an attribute name, a computed property, or a function that returns one key or several:

class Users extends Collection<User> {
  indexes = {
    email: 'email', // an attribute (or a computed property)
    role: (m) => m.get('roles'), // several keys per model, e.g. ['admin', 'editor']
  };
}

users.getBy('email', 'alice@example.com'); // the first match, in collection order
users.getAllBy('role', 'admin'); // every match
users.findWhere({ email: 'alice@example.com' }); // uses the `email` index by itself
  • Several models may share a key. getAllBy returns them all, in collection order.
  • where and findWhere use an attribute index automatically when the query includes that attribute, so existing code gets faster without changes.
  • Indexes stay current. Models are refiled as they are added, removed or changed, including on silent set calls, and before any change listener runs.
  • Indexes are lazy. One is built on its first lookup, so declaring an index you don't use costs nothing.
  • Only primitive keys are indexed. null, undefined and objects are skipped.

In Node, 5,000 findWhere lookups by one attribute on a collection of 5,000 models take 188 ms with a scan, and 3.4 ms with an index.

Events

import { EventEmitter } from '@converse/skeletor';

class Store extends EventEmitter {}

const store = new Store();
store.on('update', (data) => console.log('Updated:', data));
store.trigger('update', { key: 'value' });

// Listen to another object's events (auto-cleaned up with stopListening)
const listener = new EventEmitter();
listener.listenTo(store, 'update', (data) => console.log('Listener saw:', data));
listener.stopListening(); // removes all listeners set up via listenTo

// subscribe() returns an unsubscribe function
const unsub = store.subscribe('update', (data) => console.log(data));
unsub();

write and remodel

silent silences the events meant for side effects, such as sending or saving: change on models, and add, remove, update, reset and sort on collections. Two events fire whether or not silent is set, for state that must mirror a model or a collection, such as indexes and signals:

  • A model fires write with (model, changes, options) when attributes changed, before its change events. changes names the changed attributes and computed properties.
  • A collection fires remodel with (collection, options) when its list of models was rebuilt: models were added or removed, or their order changed. It fires once per operation, before the collection's other events, and not at all for an operation that changed nothing. It is about the list, not about a model's shape: a change to a member's attributes fires the member's write, not remodel. Unlike reset, it fires for every kind of change and doesn't say what changed. Listeners that need the added and removed models use update.
contacts.on('remodel', () => console.log('now', contacts.length, 'contacts'));
contacts.add({ id: 1 }, { silent: true }); // logs, though no `add` or `update` fires

Listeners of either event run in no set order relative to each other.

Persistence

Skeletor can persist models and collections to IndexedDB, localStorage, sessionStorage, memory, or SQLite (Node.js) with no extra packages.

Supported backends: 'local' (localStorage), 'session' (sessionStorage), 'indexed' (IndexedDB), 'memory', 'node' (SQLite, Node 22+).

Manual persistence

The traditional Backbone-style API: set storage once, call save()/fetch() explicitly.

import { Model, PersistentStorage } from '@converse/skeletor';

class Settings extends Model {
  initialize() {
    this.storage = new PersistentStorage('app-settings', 'local');
  }
}

const settings = new Settings({ id: 'main' });
await settings.fetch(); // load from localStorage
settings.set('theme', 'dark');
await settings.save(); // write to localStorage

Automatic persistence (autoSync)

Opt in once, then every write persists automatically, with no save() calls needed.

import { Model, PersistentStorage } from '@converse/skeletor';

class Settings extends Model {
  get autoSync() {
    return true;
  }

  initialize() {
    this.storage = new PersistentStorage('app-settings', 'local');
  }
}

const settings = new Settings({ id: 'main' });
await settings.hydrated; // resolves when prior data has been loaded

settings.attrs.theme = 'dark'; // persisted automatically (debounced)
settings.set('lang', 'en'); // also auto-saved

// Pass { noAutoSave: true } to suppress persistence for a specific set() call
settings.set('transient', true, { noAutoSave: true });

Pending writes are debounced (see autoSyncDelay, default 100ms) and flushed when the page is hidden (visibilitychange) or unloaded (pagehide).

When autoSync is off, hydrated is undefined, but await model.hydrated is still safe (awaiting undefined is a no-op), so code can await it uniformly.

On a Collection, autoSync is hydrate-only: the collection loads its stored state on construction but does not auto-save on add/remove/reset. To persist the contents, enable autoSync on the contained model class, so that each model writes its own record.

Note

Durability on unload is best-effort, not guaranteed. The flush on visibilitychange/pagehide is synchronous, but the underlying write may not be:

  • With synchronous backends ('local', 'session') the flush completes before the page tears down, so the last write is safe.
  • With asynchronous backends ('indexed') the flush only starts the write; the browser can kill the page before an IndexedDB transaction commits, losing the most recent debounced change. The browser gives no primitive to await a write during unload, so this is inherent rather than a bug.

visibilitychange → hidden fires earlier and far more reliably than pagehide (especially on mobile, where backgrounded tabs are killed without pagehide), so it is the real save point. To shrink the loss window further with an async backend, lower autoSyncDelay. If a write must never be lost, call await model.save() explicitly rather than relying on the unload flush.

Integrations

Skeletor has no view layer of its own. Bind it to whatever renders your UI: through signals, through subscribe(), or through events.

Signals

Skeletor state can be read through TC39 Signals. Reading a signal in a template registers the dependency, and only that binding updates when the value changes. There are no listeners to wire up, and none to forget.

Hand Skeletor the Signal your renderer uses, once, and get two functions back:

// signals.ts
import { Signal } from '@lit-labs/signals';
import { createSignals } from '@converse/skeletor';

export const { attrSignal, collectionSignal } = createSignals(Signal);
  • attrSignal(model, key) holds one attribute or computed property of a model.
  • collectionSignal(collection) holds a snapshot array of the collection's models, in collection order.
import { LitElement, html } from 'lit';
import { repeat } from 'lit/directives/repeat.js';
import { SignalWatcher, watch } from '@lit-labs/signals';
import { attrSignal, collectionSignal } from './signals';

class TodoList extends SignalWatcher(LitElement) {
  todos: Todos;

  render() {
    // Reading the collection signal re-renders the list when todos are added, removed or reordered.
    // Each `watch` updates only its own binding when that todo's title changes.
    return html`<ul>
      ${repeat(
        collectionSignal(this.todos).get(),
        (todo) => todo.cid,
        (todo) => html`<li>${watch(attrSignal(todo, 'title'))}</li>`,
      )}
    </ul>`;
  }
}
  • Pass the Signal your renderer imports. With Lit that is the one exported by @lit-labs/signals, not one from a signal-polyfill you installed yourself. A signals library only tracks signals made by its own copy. With two copies nothing throws: the view renders once and never updates. For the same reason Skeletor depends on no signals library, and apps that don't use signals pay nothing for the bridge.
  • Signals are shared. The same model and key, or the same collection, always give the same signal, and calling createSignals again with the same Signal returns the same functions.
  • Signals are read-only. State changes through the model or the collection.
  • Signals are always current, also after silent changes. They follow write and remodel, which silent doesn't silence.
  • Signals for rendering, events for side effects. Don't send a request or save from a computation that reads a signal: a silent write would trigger it. Listen for change, add and so on, which honour silent.
  • A collection signal follows the list, not its members. It gets a new array when models are added, removed, reset or reordered, and stays as it is when a member's attributes change. Read attrSignal on the member for that.
  • Collection signals are lazy. The snapshot is built when it is read, so loading thousands of models one at a time copies the array once.

Bridge signals combine in your own Signal.Computed:

const unread = new Signal.Computed(() =>
  collectionSignal(inbox)
    .get()
    .filter((m) => !attrSignal(m, 'read').get()),
);

Changing model.attributes or collection.models directly bypasses the events, and therefore the signals.

React

subscribe() plugs straight into React's useSyncExternalStore:

import { useSyncExternalStore } from 'react';

function useAttribute(model, name) {
  return useSyncExternalStore(
    (cb) => model.subscribe(cb), // subscribe: returns the unsubscribe function
    () => model.get(name), // getSnapshot
  );
}

function UserName({ user }) {
  const firstName = useAttribute(user, 'firstName');
  return <span>{firstName}</span>;
}

React calls getSnapshot on every render and re-renders whenever its result changes identity, so it must return a stable value. A single attribute works as is. Don't return model.toJSON(): it builds a new copy on every call, which makes React re-render endlessly. If you need the whole attribute object, take the copy inside the subscribe callback and return that cached copy from getSnapshot.

Marionette

Use Skeletor Models and Collections with Marionette views through @mnjs/adapters/skeletor.

Each UserName view renders a user. Clicking a name stores that user’s ID in the UserList view’s state. Each row observes the shared state, so selection changes update the buttons without rerendering the list. Start with <div id="app"></div> on the page:

import { Collection, Model } from '@converse/skeletor';
import { CollectionView, Region, View, setDataApi, setDomApi, setStateApi } from 'marionette';
import SkeletorApi from '@mnjs/adapters/skeletor';
import { html } from '@mnjs/html';
import HtmlDomApi from '@mnjs/html/marionette';

setDataApi(SkeletorApi);
setDomApi(HtmlDomApi);
setStateApi(SkeletorApi);

type Selection = {
  selectedUserId: string | number | null;
};

const UserName = View.extend({
  template: ({ firstName, isSelected }: { firstName: string; isSelected: boolean }) =>
    html`<button type="button"
      class=${isSelected ? 'is-selected' : ''}
      aria-pressed=${String(isSelected)}>${firstName}</button>`,

  modelEvents: { 'change:firstName': 'render' },
  stateEvents: { 'change:selectedUserId': 'render' },
  triggers: { 'click button': 'select:user' },

  templateContext() {
    const model = this.model as Model;
    const state = this.getState() as Model<Selection>;
    return { isSelected: state.get('selectedUserId') === model.id };
  }
});

const UserList = CollectionView.extend({
  childView: UserName,

  createState() {
    return new Model<Selection>({ selectedUserId: null });
  },

  childViewOptions() {
    return { state: this.getState() };
  },

  childViewEvents: { 'select:user': 'selectUser' },

  selectUser(child: InstanceType<typeof UserName>) {
    this.getState().set('selectedUserId', (child.model as Model).id);
  }
});

const ada = new Model({ id: 1, firstName: 'Ada' });
const users = new Collection([ada]);
const userList = new UserList({ collection: users });
new Region({ el: '#app' }).show(userList);

ada.set('firstName', 'Ada Lovelace'); // Updates the first button.
users.add({ id: 2, firstName: 'Grace' }); // Adds a second button.
// Clicking Grace marks her button with aria-pressed="true".

Try the example on CodePen.

Verified with Skeletor 4.0.3. See the adapter notes.

Design philosophy

Skeletor is a headless data layer, not an application-state framework. It owns your domain model (typed models and collections, their relationships, persistence, and server sync) and stays out of your view layer. Bind it to whatever renders your UI: Lit (through signals), React, Marionette, or plain DOM.

That scope is deliberate. Skeletor isn't trying to compete with signal libraries, Zustand, or Redux for general UI state. It bridges to signals rather than replacing them. What it's uniquely good at is giving a real, long-lived application a typed, persistent, promise-capable data layer it can adopt incrementally (above all an existing Backbone codebase that can't afford a rewrite).

Principles that follow from that:

  • Incremental over big-bang. Every feature is opt-in and backwards-compatible. Adopt attrs, computed, subscribe, or autoSync one model or one callsite at a time; nothing forces a migration.
  • Promise-capable, callback-compatible. Async operations return promises, while Backbone-style success/error callbacks and events keep working. New code can await, old code doesn't break.
  • Derive, don't duplicate. computed expresses derived values once, with caching and automatic change events.
  • Headless and framework-agnostic. No views, no router, no framework assumptions. The reactive surface is change events, subscribe(), and signals through the bridge.
  • Honest about tradeoffs. Where a guarantee can't be made (e.g. async persistence on page unload) the docs say so plainly rather than implying durability that doesn't exist (see the note under Persistence).

Direction

Skeletor is being modernized from within rather than replaced. The trajectory is a promise-first core with events and callbacks as a compatibility shim, and a reactivity model that bridges cleanly to signals, starting with createSignals. The aim is that consumers never face a migration. The library modernizes underneath them while the public surface stays stable, and the Backbone compatibility that exists today isn't sacrificed to get there.

Coming from Backbone

Migrating

If you have an existing Backbone project, you can migrate the data layer incrementally:

  1. Install Skeletor: npm install @converse/skeletor
  2. Replace import Backbone from 'backbone' with named imports: import { Model, Collection } from '@converse/skeletor'
  3. Replace Backbone.Model.extend({...}) with class MyModel extends Model { ... }
  4. Fix the handful of removed or renamed methods listed below
  5. Keep using Backbone for Views, Router, and History — they are unaffected

Your Views and Router don't need to change at all. Skeletor models and collections emit the same events Backbone does.

Modernizations

  • Rewritten in TypeScript with full type definitions
  • Removed the dependency on jQuery
  • Replaced underscore with lodash-es, with individual imports for tree-shaking
  • Uses native browser APIs instead of lodash wherever possible
  • Drops support for older browsers (including IE); requires ES6+
  • All types (Model, Collection) are ES6 classes — use class extends instead of .extend()
  • Adds EventEmitter mixin class (replaces the old Events constructor function)
  • Async operations return Promises
  • Collection indexes on any attribute, computed property or function, not just id
  • A write event, fired before the change events and also for silent writes, for state that must mirror a model (indexes, signals). silent now only silences the change events, and all listeners hear write too.
  • A remodel event on collections, the counterpart of write: fired once per operation that changed the models or their order, silent or not, before add, remove, update, reset and sort.
  • A signals bridge, createSignals, for renderers that track TC39 Signals, such as Lit.

What was removed

  • View and ElementView — manage your UI separately
  • Router and History — use the browser's History API or a dedicated router library
  • .extend() static method — use class MyModel extends Model instead
  • clone() on Model — use new MyModel(model.toJSON()) instead
  • chain() and escape() on Model
  • inject, foldl, foldr on Collection — use reduce instead
  • sample, take, tail, initial on Collection
  • without, reject, select on Collection — use filter instead
  • invoke (Lodash: invokeMap) on Collection: use map instead
  • partition on Collection

Method renames (Underscore → Lodash)

Old (Underscore) New (Lodash)
rest drop
indexBy keyBy
contains includes

Other behavioural changes

  • Collection.prototype.forEach no longer returns the iterated items. Use map instead.
  • Model.prototype.set returns null (not false) when validation fails.
  • Collection.prototype.create returns null (not boolean) on failure.

Contributing

Use the Node version in .nvmrc for development. The tests run in a browser through Karma.

npm install
make check       # type check, tests, and lint (what CI runs)
npm run dev      # tests in watch mode
npm run build    # bundles into dist/

Questions and discussion are welcome in the Converse XMPP chat room.

Changelog

See CHANGES.md.

License

MIT. See LICENSE.


Skeletor

About

Models and Collections for modern web apps

Topics

Resources

Stars

16 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages