# Marionette 5.0.0-beta.1 documentation bundle Version: 5.0.0-beta.1 Channel: next Publication: beta (published on npm) Source revision: b06750c507494441f0b2298766b70087e45346a2 Local changes: false Content SHA-256: 3fe8788a771994d9effd124fee94d7444637a27ec974a5b520ccbf43b55bbec9 Read individual documents for focused tasks. Each section below contains the exact published reading Markdown, including its source identity. --- Document: docs/readme.md Canonical URL: https://marionettejs.com/docs/ Markdown URL: https://marionettejs.com/docs/index.md Reading SHA-256: 7f73d9a4ff2f5ec0af5843ea7b954c0afc6160d925850f54e98cc702e060a668 # Build your first piece of UI A View handles a piece of the interface. A Region puts it on the page and cleans it up when it is replaced. Start there; add the other pieces when you need them. ## Where do you want to start? - **[Build something](/docs/installation.md#quick-start)** — set up Marionette and show your first View. - **[Work with an agent](/docs/agents.md)** — give your agent the right contract and a concrete task. - **[Look up an API](/docs/public-api.md)** — find the class, method, or integration you need. ## A button that does something With a [matching v5 build](/docs/installation.md#install) installed, add a place for the View in your HTML: ```html
``` Then run this module in your application: ```javascript import { Region, View } from 'marionette'; const Counter = View.extend({ initialize() { this.count = 0; }, template: ({ count }) => ``, templateContext() { return { count: this.count }; }, events: { 'click button': 'increment' }, increment() { this.count += 1; this.el.querySelector('span').textContent = String(this.count); } }); export const region = new Region({ el: '#app' }); region.show(new Counter()); ``` Click the button: **Count: 0 → Count: 1 → Count: 2**. The View handles the click and updates the number in place. The button stays the same DOM element. When that part of the screen is finished, `region.empty()` destroys the View and removes its event handlers. The `#app` mount remains, ready for the next View. ## Give it a little more to do | You want to… | Next step | | --- | --- | | Show a list that changes | [Render children with CollectionView](/docs/collection-view.md) | | Open a detail screen | [Show and replace a View](/docs/region.md) | | Save a form without losing a draft | [Forms and accessibility](/docs/forms-and-accessibility.md) | | Connect an existing router or data source | [Choose integrations](/docs/choosing-integrations.md) | | Check that it works | [Test an application](/docs/testing.md) | You can keep Backbone models, an existing router, or a preferred template system. Choose each integration for the job it does; the button above needs none of them. For versions before v5, see the [backbone.marionette repository](https://github.com/marionettejs/backbone.marionette). [Canonical source](/docs/markdown/docs/readme.md) · [Source identity](/docs/manifest.json) --- Document: docs/installation.md Canonical URL: https://marionettejs.com/docs/installation/ Markdown URL: https://marionettejs.com/docs/installation.md Reading SHA-256: fdd88cef2835ae795727e379c4d6e928eb88292020a0fc57c0ffb5a7e8808b77 # Installing Marionette Install the core package, show a View, then add the integrations your application needs. Native DOM APIs, plain objects, and function templates work out of the box. This guide covers the published Marionette 5.0.0-beta.1 package and its matching companion packages. ## Documentation Index * [Install](#install) * [Peer dependencies](#peer-dependencies) * [Quick start](#quick-start) * [TypeScript](#typescript) * [Independent runtimes](#independent-runtimes) * [Observable data sources](#observable-data-sources) * [Distribution formats](#distribution-formats) * [Backbone is optional](#backbone-is-optional) * [jQuery DOM adapter is optional](#jquery-dom-adapter-is-optional) * [DOM content adapters are optional](#dom-content-adapters-are-optional) * [Current v5 documentation](/docs/index.md) ## Install The v5 package name is `marionette`. ```bash npm install marionette@5.0.0-beta.1 ``` The beta is available on npm. Pin this exact version and use the matching documentation. For unreleased changes, build and pack a known source revision separately. > The v4 package name has changed. See the [upgrade guide](/docs/upgrade-guide.md) > for migration guidance from earlier releases. Core and `@mnjs/data` automatically install the matching `@mnjs/utils` version. Applications do not need a separate install unless they import helpers directly. During prereleases, keep Marionette packages on the same version. See the [shared helpers](/docs/common.md#shared-helpers) for reusable component helpers. ## Peer dependencies Marionette v5 core has no peer dependencies. The separate `@mnjs/adapters` package requires the matching Marionette version and declares the integration-specific peers as optional. | Peer | Required? | When you need it | |---|---|---| | `marionette` `5.0.0-beta.1` | Required | The matching core runtime configured with an adapter. | | `backbone` `^1.4.0` | Optional | Only if your app imports `@mnjs/adapters/backbone`. See [Backbone is optional](#backbone-is-optional). | | `@types/backbone` `^1.4.23` | Optional | TypeScript declarations for `@mnjs/adapters/backbone`. JavaScript consumers do not need it. | | `jquery` `^4.0.0` | Optional | Only if your app uses the `@mnjs/adapters/dom/jquery` adapter. See [jQuery DOM adapter is optional](#jquery-dom-adapter-is-optional). | | `@types/jquery` `^4.0.1` | Optional | TypeScript declarations for `@mnjs/adapters/dom/jquery`. JavaScript consumers do not need it. | | `morphdom` `^2.7.8` | Optional | Only if your app imports `@mnjs/adapters/dom/morphdom`. | | `lit-html` `^3.3.3` | Optional | Only if your app imports `@mnjs/adapters/dom/lit-html`. | Optional peers are installed only when you opt into them: ```bash # Only if you use the Backbone integration npm install @mnjs/adapters@5.0.0-beta.1 backbone # Only if you use the jQuery DomApi adapter npm install @mnjs/adapters@5.0.0-beta.1 jquery # Only if you use XState actors npm install @mnjs/adapters@5.0.0-beta.1 xstate ``` The XState actor adapter does not import or declare XState as a peer. Install XState alongside the adapter; the adapter consumes its public actor shape. Npm does not install missing optional peers. TypeScript consumers of an optional subpath must install its matching type package explicitly: ```bash # Only if TypeScript imports @mnjs/adapters/backbone npm install --save-dev @types/backbone@^1.4.23 # Only if TypeScript imports @mnjs/adapters/dom/jquery npm install --save-dev @types/jquery@^4.0.1 ``` Marionette core does not import or require Underscore. Install it as an application dependency only when your own code uses it, such as an `_.template` used by a View. ## Quick start Marionette v5 exposes its public API through named ESM imports. There is no default-namespace export; use named imports only. Add a mount element to the page before running the module: ```html
``` ```js import { Application, View } from 'marionette'; const RootView = View.extend({ template: () => '
Hello, Marionette.
' }); const app = new Application({ region: document.getElementById('app'), onStart() { this.showView(new RootView()); } }); await app.start(); ``` `View` and `CollectionView` accept a DOM element for `el`. They do not resolve selector strings — pass `document.querySelector('#root')` at the call site. See the [upgrade guide](/docs/upgrade-guide.md) for the migration entry. `Region` continues to accept selector strings. ## TypeScript Marionette 5.0.0-beta.1 includes declarations for TypeScript 6 and 7, with ESM and CommonJS entrypoints. Core needs no separate `@types` package. Annotate `initialize` to describe a View's application options; TypeScript uses that signature to check construction and `this.options`. ```ts import { View } from 'marionette'; const MessageView = View.extend({ template: false, initialize(options: { message: string }) { this.el.textContent = options.message; }, message(): string { return this.options.message; } }); const view = new MessageView({ message: 'Hello, Marionette.' }); document.body.append(view.render().el); ``` This View requires a string `message`. Missing options or a numeric message are compile errors. `template: false` preserves the text set during initialization. Named imports work with `NodeNext` or bundler module resolution. The [consumer TypeScript guide](/docs/typescript.md) covers application options, DOM events, module resolution, and inheritance choices. Optional integrations may need their own type packages, listed above. ## Independent runtimes The named root exports form one default runtime. Use `createMarionette()` only when independent applications in the same process need isolated classes, adapters, renderer configuration, or Radio channels: ```javascript import { createMarionette } from 'marionette'; const isolated = createMarionette(); const IsolatedView = isolated.View.extend({ template: () => 'Independent' }); ``` See [Runtime isolation](/docs/runtime-isolation.md) for composition and ownership rules. ## Observable data sources Core's default DataApi supports plain objects and static arrays without a required dependency. Backbone Models and Collections are observable sources too; retain them through the [Backbone adapter](/docs/backbone.md) when the application already uses them. For a new application needing observable Model and ordered Collection sources, the optional `@mnjs/data` package is the native choice: ```bash npm install @mnjs/data@5.0.0-beta.1 ``` Configure its adapters before constructing owners. See the [`@mnjs/data` guide](/docs/data-api.md#optional-mnjsdata-sources) for a complete adapter setup and rendered list example. Applications using XState actors can select an ordered array of child actor references through `@mnjs/adapters/xstate`. See [XState actors](/docs/data-api.md#xstate-actors). ## Distribution formats ES modules are the canonical path for new applications. Use `import` syntax so package export conditions select the ESM entry, and use Marionette's named exports. Marionette also ships compatibility distributions throughout v5: - CommonJS supports legacy Node and build-tool consumers through `require('marionette')`. - Unminified and minified UMD builds support no-bundler, AMD, and `Marionette`-global consumers. All four ESM, CommonJS, unminified UMD, and minified UMD outputs remain supported and distribution-validated for v5. Marionette will not add another format or switch to unbundled source modules without measured consumer benefit. Six months after v5.0.0 is published, the distribution review is an evidence checkpoint for a future major version, not a removal commitment. ## Backbone is optional Starting with v5, Marionette core does not depend on Backbone at runtime. Plain objects and arrays use the default DataApi. Applications passing Backbone Models or Collections to Marionette must configure the Backbone DataApi before constructing those consumers: ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import { setDataApi } from 'marionette'; setDataApi(BackboneApi); ``` This configures model and collection use. Select the StateApi role separately when an owner uses Backbone state; see [Optional Backbone](/docs/backbone.md). [Data API](/docs/data-api.md) describes the neutral runtime contract. ## jQuery DOM adapter is optional Marionette v5 core is jQuery-free. The default DOM API uses native browser methods, and `view.$(selector)` returns a `NodeList`. Applications that want jQuery-shaped results from Marionette's DOM helpers — for example, `view.$(selector)` returning a jQuery collection — can opt into the optional `@mnjs/adapters/dom/jquery` adapter at app boot: ```javascript import { setDomApi } from 'marionette'; import JQueryDomApi from '@mnjs/adapters/dom/jquery'; setDomApi(JQueryDomApi); ``` The adapter imports `jquery`, so this integration requires `jquery` only when you select that adapter. If existing code also uses `$el`, assign `this.$el = $(this.el)` in its View, CollectionView, or Behavior `initialize()` method. See the [upgrade guide](/docs/upgrade-guide.md) for the migration entries on jQuery DOM compatibility and the `detachContents` policy. ## DOM content adapters are optional Use the same `@mnjs/adapters` package for incremental rendering. Install only the DOM library you select: ```bash npm install @mnjs/adapters@5.0.0-beta.1 morphdom # or npm install @mnjs/adapters@5.0.0-beta.1 lit-html ``` Import `MorphdomDomApi` from `@mnjs/adapters/dom/morphdom`, or `LitDomApi` from `@mnjs/adapters/dom/lit-html`, and pass it to `ViewClass.setDomApi()` before creating instances. Each adapter preserves unrelated DOM operations. Lit supplies the attachment hooks its directives need. DataApi and StateApi configuration remains explicit and separate. See [Rendering to DOM](/docs/rendering.md#rendering-to-dom) for examples and lifecycle requirements. ## Getting Started [Choose a class for the job](/docs/classes.md), or learn the [shared configuration patterns](/docs/basics.md). [Canonical source](/docs/markdown/docs/installation.md) · [Source identity](/docs/manifest.json) --- Document: docs/beta.md Canonical URL: https://marionettejs.com/docs/beta/ Markdown URL: https://marionettejs.com/docs/beta.md Reading SHA-256: 136904dde3bd7dd4f0888a6c6fed9fb0297d2dc1eb3e4e7936ec4797d3a6040a # Try Marionette v5 beta `5.0.0-beta.1` is published on npm and ready for application trials. Install the exact registry version. A locally built artifact with the same version string may differ from the published release. ## What beta means The intended architecture is ready for application trials: named core imports, View and Region ownership, synchronous UI lifecycle, Application asynchronous coordination, optional data/state providers, and first-party package declarations. Use those documented public contracts. Beta feedback can still change an API before stable; record any change in migration guidance and the release notes. This beta makes no comparative agent-effectiveness claim. The public corpus remains an unscored prototype. Architecture lint, generated method metadata, development inspection, and additional test helpers are separate work, not installed features. Core is `marionette`. The companion packages are `@mnjs/utils`, `@mnjs/radio`, `@mnjs/data`, and `@mnjs/adapters`. Keep all package versions aligned; install optional providers only when needed. See [the migration ledger](/docs/migration-from-v4.md) and [upgrade guide](/docs/upgrade-guide.md). Older registry alphas are different implementations and do not define this beta's API. ## Start in an empty directory Install core and the optional native data package explicitly: ```sh mkdir my-marionette-app cd my-marionette-app npm init -y npm install marionette@5.0.0-beta.1 @mnjs/data@5.0.0-beta.1 cp -R node_modules/marionette/dist/docs/starter ./starter cd starter npm install marionette@5.0.0-beta.1 @mnjs/data@5.0.0-beta.1 npm test npm run build npm run dev ``` The starter README explains its files and trial steps. It is also available in the [source tree](https://github.com/marionettejs/marionette/tree/master/test/fixtures/data-package-starter). Copying uses a new directory and preserves existing application files. The commands above use a POSIX shell; on Windows, copy the same folder using your file manager. Before publication, replace each runtime install with one `npm install` invocation containing all five absolute candidate tarball paths. The required companions are not assumed to exist on npm. Use artifacts from the same `release-evidence.json`; keep their SHA-512 checksums and source commit with your trial report. Do not use `npm link`, a Git dependency, or source imports as proof of the published install path. The starter has editable rows, asynchronous local selection, deliberate cancellation, and teardown. It has no backend, persistence, or URL router. Connect its `navigate` function to the application's chosen router when URLs are needed. See [routing](/docs/routing.md) for loader failure, navigation away, and stop/restart rules. Use [TypeScript guidance](/docs/typescript.md) when adding typed application code. ## Check a real feature 1. Edit a row title without opening it. Reverse rows; the draft should survive. 2. Open the slow first note, then immediately open the second. The second should remain. 3. Change a module during `npm run dev`. The old workspace should release its handlers. 4. Run `npm test` and `npm run build`. Add a regression for your application's behavior. 5. Test keyboard focus and selection in a real browser using the actual DOM adapter. 6. Install the [consumer agent skill](/docs/agent-tools.md) if useful, then ask it to locate the installed docs and identify the component responsible for cancellation. The installed-consumer fixture checks the starter outside the repository against candidate tarballs. The browser release matrix checks its draft, focus, selection, stale-load suppression, and handler cleanup in Chromium, Firefox, and WebKit. Those checks do not establish accessibility for an entire application or a router's history/deployment behavior. ## Report feedback [Open a reproducible issue](https://github.com/marionettejs/marionette/issues/new/choose) with the exact package versions/source revision, selected providers, browser and bundler, expected behavior, actual behavior, and a minimal anonymous reproduction. Prioritize installation problems, incorrect declarations, lost editable state, late navigation commits, leaked subscriptions, and confusing documentation. Do not include private application code or customer data. ## Before publication A beta needs verified scope/publisher access for all five packages, a clean candidate commit, and the full [exact-artifact validation](https://github.com/marionettejs/marionette/blob/b06750c507494441f0b2298766b70087e45346a2/docs/release-promotion.md#dry-run). Review the beta notes, migration guidance and installed starter together. Record known failures instead of claiming the beta is stable. Registry installation must be checked immediately after publication; local tarball tests cannot prove npm permission, propagation, or trusted-publisher configuration. ## If the beta fails in your application Pin your previous working dependency versions and restore the matching application code and lockfile. The old `marionette@5.0.0-alpha.2` is not an API-compatible rollback for this candidate; there is currently no previous published matching five-package release. Existing v4 applications should retain their pre-migration revision and `backbone.marionette` lockfile until their beta trial succeeds. Maintainers must not overwrite a published beta version. Withdraw its recommendation, deprecate a broken version with a specific reason, and publish a corrected beta. Move `next` only to a verified compatible prior release; if beta.1 is the first one, there is no earlier beta to select. Preserve exact artifacts and failure evidence. See [release recovery](https://github.com/marionettejs/marionette/blob/b06750c507494441f0b2298766b70087e45346a2/docs/release-promotion.md#recovery-and-rollback). [Canonical source](/docs/markdown/docs/beta.md) · [Source identity](/docs/manifest.json) --- Document: docs/agents.md Canonical URL: https://marionettejs.com/docs/agents/ Markdown URL: https://marionettejs.com/docs/agents.md Reading SHA-256: 9911ce2b807e2139c7120e3486c768b60df95e34d85a7fc0b785cae8d33d1ecb # Build with Marionette Use this guide when an agent is building or maintaining an application with Marionette. It links each decision to the same contracts a human reviewer uses. For changes to Marionette itself, use the [maintainer guide](https://github.com/marionettejs/marionette/blob/b06750c507494441f0b2298766b70087e45346a2/docs/maintainers/readme.md). ## Establish the installed contract Before choosing an API, inspect the application's package manifest, lockfile, installed declarations, and existing Marionette configuration. Record: - the installed `marionette` version and matching optional package versions; - whether the dependency comes from a published package, Git commit, or local build; - the source revision for a checkout or custom artifact; - the selected renderer, data/state sources, DOM integrations, and router. This documentation matches the published Marionette 5.0.0-beta.1 package. A website example, a copied prompt, or a third-party search result is not proof that another installed version has that API. Check the installed version, exports, and declarations; reproduce uncertain behavior with a small test against that package. For a fresh application, follow [installation](/docs/installation.md). For a v4 application, use the [migration guide](/docs/migration-from-v4.md) and [upgrade guide](/docs/upgrade-guide.md) before applying current patterns. Do not silently upgrade dependencies to make an example fit. ## Read for the task | Task | Start here | Verify | | --- | --- | --- | | Show or update a piece of UI | [View](/docs/view.md), [rendering](/docs/rendering.md) | The intended element and content change; relevant handlers still work after rendering. | | Replace part of a screen | [Region](/docs/region.md), [View lifecycle](/docs/lifecycle.md) | The outgoing View is cleaned up and the new View owns the intended mount. | | Render a changing list | [CollectionView](/docs/collection-view.md), [DataApi](/docs/data-api.md) | Stable item identity, correct ordering, removal cleanup, and preservation of surviving edits. | | Coordinate a feature or navigate | [Application](/docs/application.md), [routing](/docs/routing.md) | Startup success, stale navigation, failure, stop, and destruction. | | Choose data, state, rendering, or DOM integration | [Choosing integrations](/docs/choosing-integrations.md) | The chosen capability matches the source; configuring one integration does not implicitly configure another. | | Add local or shared state | [State sources](/docs/state.md) | The correct observer updates; destroying one borrower does not dispose shared state. | | Handle DOM or component events | [DOM interactions](/docs/dom-interactions.md), [events](/docs/events.md) | One intended response per interaction and no response after teardown. | | Diagnose a framework error | [Diagnostic catalog](/docs/diagnostics.md) | The invariant associated with the diagnostic code; do not match only error-message text. | Read the relevant page and its direct references. Load the full documentation only when the task requires a broader API review. ## Choose the smallest supported pattern Keep the application's established integrations unless the task requires changing them. For new code, start with the built-in defaults: native DOM APIs, function templates, and plain objects or arrays. Plain sources are not observable; update the UI explicitly or select an observable integration when the task needs one. Choose data, state, rendering, and DOM capabilities independently. Follow the [integration decision order](/docs/choosing-integrations.md) before writing a custom adapter. Record the chosen provider and its registration point once in the application's own architecture notes so later agents do not choose again. Use a View for interface ownership, a Region for placement, and a CollectionView for repeated children. Use an Application when work has an asynchronous feature lifecycle. A plain function or class is enough when it needs none of these contracts. The [class guide](/docs/classes.md) explains the boundaries. Configure the selected runtime before creating its consumers. The default named exports share a runtime. Use [runtime isolation](/docs/runtime-isolation.md) when independent configurations must coexist; do not create a runtime per View. ## Make ownership and cancellation explicit For each resource, name the owner and the operation that releases it. Let the owning Region or CollectionView manage its child Views through public APIs. Use [View lifecycle hooks](/docs/lifecycle.md) for external listeners, timers, and widgets according to their actual render, attachment, and destruction lifetime. A rerender must not accumulate resources; destroying a View must not leave them running. A supplied `state` source is borrowed. A `createState()` result is owned and uses the configured StateApi's optional disposal hook when its owner is destroyed. Marionette does not infer ownership from which object first reads a source. Await Application lifecycle operations when later work depends on their result. They return `Promise`: `true` means the target state was reached; `false` means the request was superseded. A current readiness failure rejects. Keep those outcomes distinct. Constructor hooks run synchronously, and completion hooks are synchronous notifications; returning a Promise from them does not add readiness. Pass the readiness hook's signal to cancellable work. After an asynchronous step, check that it still belongs to the active operation before committing application side effects. Marionette suppresses stale lifecycle completion; it cannot undo an arbitrary write made by application code. Follow the complete [routing pattern](/docs/routing.md) for navigation and feature startup. ## Prove the behavior in the application Use the application's existing test runner, scripts, and package manager. Library maintenance commands are not a consumer project's test strategy. Test the successful interaction and the boundary most likely to break. For an asynchronous screen, navigate away while work is pending and ensure its stale result cannot replace the current screen. For a list, edit a surviving row while inserting, removing, or reordering another row. For a subscription, destroy one consumer and confirm the remaining consumer still receives updates. Use a real browser when correctness depends on focus, attachment, DOM event propagation, or editable state. A build or screenshot alone does not prove those interactions. Use documented public APIs for assertions rather than private framework fields. When reporting a change, name the behavior, the tested package/source, the exact commands or interactions performed, and any untested boundary. Keep changes focused and avoid introducing runtime instrumentation merely to help an agent understand the code. ## Use agent tools as another way to read the same docs Follow [Set up an agent](/docs/agent-tools.md) to install the consumer skill and read version-matched packaged docs. Adapt the [application instruction template](/docs/application-agent-template.md) to preserve this project's actual decisions across tasks. A Markdown page or versioned documentation index can be read directly. A service such as Context7 can help locate the relevant passage, but verify its library and version selection before using the result. When retrieval is unavailable, use the same source documents in the repository or the matching documentation artifact. A documentation index does not install instructions into every agent. An application's own agent instructions should link to this guide and record its installed version and architecture choices. They should not copy this entire guide or use this library's maintainer instructions as application policy. Use playground tools only to examine the example they control. Their results do not establish behavior in your application. No hosted AI service or MCP server is required to use Marionette or follow this workflow. [Canonical source](/docs/markdown/docs/agents.md) · [Source identity](/docs/manifest.json) --- Document: docs/classes.md Canonical URL: https://marionettejs.com/docs/classes/ Markdown URL: https://marionettejs.com/docs/classes.md Reading SHA-256: e55e03ae39732d7b536522e0f38c71ce4179b21b14e8ed05970eb4f84cd02a7b # Marionette Classes Each Marionette class has a job: render a piece of interface, manage where it goes, repeat it, share an interaction, or coordinate a feature. Start with the job you need, then follow the reference for its options and lifecycle. The classes share [configuration and inheritance patterns](/docs/basics.md#class-based-inheritance) and a [common set of methods](/docs/common.md). ## [Marionette.View](/docs/view.md) A `View` owns a piece of interface through its root element, `el`. It renders a template, handles DOM interactions, and can divide a screen into Regions for child Views. Plain objects and function templates work with the default configuration. `View` includes: - [The DOM API](/docs/dom-api.md) - [Class Events](/docs/class-events.md#view-events) - [DOM Interactions](/docs/dom-interactions.md) - [Child Event Bubbling](/docs/events.md#event-bubbling) - [Entity Events](/docs/entity-events.md) - [View Rendering](/docs/rendering.md) - [Prerendered Content](/docs/prerendered-dom.md) - [View Lifecycle](/docs/lifecycle.md) A `View` can have [`Region`s](#marionetteregion) and [`Behavior`s](#marionettebehavior) ## [Marionette.CollectionView](/docs/collection-view.md) A `CollectionView` manages an ordered set of child Views inside its root element. Use it for rows, cards, or other repeated content. A plain array supplies a static collection; an observable data integration can notify it of changes. You can also manage child Views directly without supplying a collection. `CollectionView` includes: - [The DOM API](/docs/dom-api.md) - [Class Events](/docs/class-events.md#collectionview-events) - [DOM Interactions](/docs/dom-interactions.md) - [Child Event Bubbling](/docs/events.md#event-bubbling) - [Entity Events](/docs/entity-events.md) - [View Rendering](/docs/rendering.md) - [Prerendered Content](/docs/prerendered-dom.md) - [View Lifecycle](/docs/lifecycle.md) A `CollectionView` can have [`Behavior`s](#marionettebehavior). ## [Marionette.Region](/docs/region.md) A `Region` gives a View a place to appear. Showing a new View renders and attaches it; replacing or emptying the Region destroys its current View by default. `Region` includes: - [Class Events](/docs/class-events.md#region-events) - [The DOM API](/docs/dom-api.md) ## [Marionette.Behavior](/docs/behavior.md) A `Behavior` shares interaction logic between Views, such as keyboard shortcuts or a reusable button action. The host View constructs and cleans up its Behaviors. `Behavior` includes: - [Class Events](/docs/class-events.md#behavior-events) - [DOM Interactions](/docs/dom-interactions.md) - [Entity Events](/docs/entity-events.md) ## [Marionette.Application](/docs/application.md) An `Application` coordinates a feature's asynchronous start, stop, restart, and destruction. It can own child Applications and display a View through an optional Region. Use it for work that should start and stop together. `Application` includes: - [Class Events](/docs/class-events.md#application-events) - [Radio API](/docs/radio.md#marionette-integration) - [Common Marionette Functionality](/docs/common.md) - [State API](/docs/state.md) An `Application` can have a single [region](/docs/application.md#application-region). ## [Marionette.MnObject](/docs/mn-object.md) `MnObject` gives a nonvisual object initialization, events, options, and cleanup. Use it when those conventions are useful without an element or an Application's asynchronous lifecycle. `MnObject` includes: - [Class Events](/docs/class-events.md#mnobject-events) - [Radio API](/docs/radio.md#marionette-integration). ## [State sources and StateApi](/docs/state.md) Give a feature or View its own state, or pass in a source it should share. `StateApi` connects that source's notifications and cleanup to its owner. ## Routing in Marionette Choose a router that fits your application. Route handlers can start an Application or show a View using ordinary application code. [Continue Reading](/docs/routing.md) about routing in Marionette. [Canonical source](/docs/markdown/docs/classes.md) · [Source identity](/docs/manifest.json) --- Document: docs/basics.md Canonical URL: https://marionettejs.com/docs/basics/ Markdown URL: https://marionettejs.com/docs/basics.md Reading SHA-256: 38df7b22ced5ac44884ecb3f86cec653e494afa002ae2ae9592a072f2f32302a # Common Marionette Concepts Learn the configuration patterns once, then use them across Marionette's classes. Each class's reference explains when it reads an option and whether it reads it again. For checked application options, see the [TypeScript example](/docs/installation.md#typescript). ## Documentation Index * [Importing Marionette](#importing-marionette) * [Class-based Inheritance](#class-based-inheritance) * [Value Attributes](#value-attributes) * [Functions Returning Values](#functions-returning-values) * [Binding Attributes on Instantiation](#binding-attributes-on-instantiation) * [Common Marionette Functionality](/docs/common.md) ## Importing Marionette Install the v5 `marionette` package and use named imports: ```javascript import { Application, View } from 'marionette'; const view = new View(); const app = new Application(); ``` V5 has no default namespace export. The separate `@mnjs/adapters` package provides optional integration subpaths; see [Installing Marionette](/docs/installation.md) for the entrypoints and their dependencies. Existing no-bundler applications may serve the published `dist/marionette.umd.js` artifact. It exposes the named API on the global `Marionette` object and supports `Marionette.noConflict()`. Package-based named imports are the canonical path for new applications. ## Class-based Inheritance Like [Backbone](http://backbonejs.org/#Model-extend), Marionette provides a pseudo-class `extend` method. [All built-in classes](/docs/classes.md), such as `View` and `MnObject`, provide this method. The `protoProps` and `staticProps` hashes passed to `extend` contribute their own enumerable string and symbol keys. Non-enumerable and inherited input properties are ignored, except that an own `constructor` selects the child constructor even when it is non-enumerable. Enumerable string statics from the parent, including inherited ones, are copied to the child constructor. In the example below, we create a new pseudo-class called `MyView`: ```javascript import { View } from 'marionette'; const MyView = View.extend({}); ``` You can now create instances of `MyView` with JavaScript's `new` keyword: ```javascript const view = new MyView(); ``` ### Value Attributes When we extend classes, we can provide class attributes with specific values by defining them in the object we pass as the `extend` parameter: ```javascript import { View } from 'marionette'; const MyView = View.extend({ className: 'bg-success', template: () => '
', regions: { myRegion: '.my-region' }, modelEvents: { change: 'removeBackground' }, removeBackground() { this.el.classList.remove('bg-success'); } }); ``` When `MyView` creates its element, the element receives the `bg-success` class. When the View renders, the `myRegion` Region targets `.my-region` within that element. Entity-event behavior is documented separately because it depends on an attached entity. ### Functions Returning Values Many configuration attributes accept either a value or a function returning that value. Attributes documented as value callbacks call the function with the Marionette instance as `this`. A `template` function is the renderer itself and instead receives serialized data as its argument; it does not receive the View as `this`. Resolution timing is part of each attribute's contract; do not assume every function runs during construction or that every result is cached for the object's lifetime. ```javascript import { View } from 'marionette'; let cancelCalls = 0; let defaultCalls = 0; let overrideCalls = 0; let templateContext; let templateData; const MyView = View.extend({ options() { this.optionsResolutionCount = (this.optionsResolutionCount || 0) + 1; return { count: 1, enabled: true, label: 'default', tone: 'quiet' }; }, className() { this.classNameResolutionCount = (this.classNameResolutionCount || 0) + 1; return `notice-${this.getOption('tone')}`; }, template(data) { templateContext = this; templateData = data; return ''; }, triggers: { 'click .cancel': 'cancel:default', 'click .save': 'save:default' }, }); const view = new MyView({ count: 0, enabled: false, label: null, tone: 'urgent', triggers: { 'click .save': 'save:override' }, }); const classNameBeforeRender = view.el.className; view.on('cancel:default', () => { cancelCalls += 1; }); view.on('save:default', () => { defaultCalls += 1; }); view.on('save:override', () => { overrideCalls += 1; }); view.render(); view.el.querySelector('.save').click(); view.el.querySelector('.cancel').click(); export { cancelCalls, classNameBeforeRender, defaultCalls, overrideCalls, templateContext, templateData, view }; ``` Here `options()` supplies class defaults, the constructor's `tone` wins, and `className()` resolves while the View creates its element. The constructor's `triggers` map replaces the class map rather than merging with it. ### Function Context Use a normal method when a configuration callback needs the instance context. An arrow function retains its surrounding lexical `this`, so it is appropriate only when the callback does not need the Marionette instance. ### Binding Attributes on Instantiation The documented constructor options for each class can replace matching values defined on its prototype. This supports runtime configuration such as a View's events, triggers, model, collection, and Region definitions: ```javascript import { View } from 'marionette'; const MyView = View.extend({ template: () => 'Details' }); const myView = new MyView({ triggers: { 'click a': 'show:link' } }); ``` This will set a trigger called `show:link` that will be fired whenever the user clicks an `` inside the view. Constructor values replace matching class values; map options are not implicitly deep-merged. For example: ```javascript import { View } from 'marionette'; const MyView = View.extend({ template: () => 'Details', triggers: { 'click @ui.save': 'save:form' } }); const myView = new MyView({ triggers: { 'click a': 'show:link' } }); ``` In this example, `show:link` is the only configured trigger. The constructor's `triggers` object completely replaces the class-defined object. ## Setting Options Every Marionette class stores its merged class defaults and constructor values on `this.options`. `getOption(name)` reads a defined value from `this.options` before falling back to the instance. A constructor value of `false`, `null`, or `0` therefore remains an intentional override; only `undefined` falls through. Resolved class defaults and constructor option hashes contribute their own enumerable string and symbol properties when Marionette builds `options`. Inherited and non-enumerable properties are ignored. `mergeOptions` copies only the requested own enumerable string options onto an instance. ```javascript import { View } from 'marionette'; const MyView = View.extend({ checkOption() { console.log(this.getOption('foo')); } }); const view = new MyView({ foo: 'some text' }); view.checkOption(); // prints 'some text' ``` Constructor/default option merges use own enumerable string and symbol properties. See [`getOption` and `mergeOptions`](/docs/common.md#getoption) for the exact lookup and copying boundaries. ## Common Marionette Functionality Marionette has a few methods and core functionality that are common to [all classes](/docs/classes.md). [Continue Reading...](/docs/common.md). [Canonical source](/docs/markdown/docs/basics.md) · [Source identity](/docs/manifest.json) --- Document: docs/terminology.md Canonical URL: https://marionettejs.com/docs/terminology/ Markdown URL: https://marionettejs.com/docs/terminology.md Reading SHA-256: 7f32fedf7105689e6873026e967d7bc061b117def920c7f3b55c99b877aee44e # Terms used in these guides These names describe what a value does, where it belongs, and who cleans it up. The distinctions matter when connecting data, composing Views, or waiting for an Application to finish starting. ## Models, template data, and state A **model** is one value displayed by a View or represented by a CollectionView's child View. It may be a plain object or a value from your chosen data library. An **ordered model snapshot** is the current sequence returned by `DataApi.models(collection)`. Collection change records refer to those original models through `added`, `removed`, `previous`, and `current`. **Serialized data** is the value prepared for a template. The default `serializeCollection()` returns each model's serialized value; it does not return the raw model snapshot. An override may return another shape. When the View has no model, its template receives that collection serialization result as `models`. See [Rendering](/docs/rendering.md). A **state source** holds state for an Application, MnObject, View, CollectionView, or Behavior. `getState()` returns the source itself, with its own values and methods. State is configured separately from the model or collection a View displays. See [State sources](/docs/state.md). | API | What it connects | | --- | --- | | [`DataApi`](/docs/data-api.md) | Model reads, template serialization, collection order, and data events. | | [`StateApi`](/docs/state.md#stateapi) | State events and cleanup of owned state. | | [`DomApi`](/docs/dom-api.md) | Element creation, selection, content, and attachment. | An **adapter** implements the methods for one or more of these APIs using your chosen tools. Installing an integration package makes its adapter available; configure it on the runtime or class that will use it. DataApi, StateApi, and DomApi support partial overlays: supplied methods replace the corresponding methods, while omitted methods remain inherited. An EventDelegator is a complete replacement. See [Choosing integrations](/docs/choosing-integrations.md) before selecting or implementing an adapter. ## Ownership and cleanup A Behavior's **host View** is the View it is attached to. A **child View** is shown by a Region or managed by a CollectionView. These names describe relationships; a particular child might be a row, a card, or another item in your interface. A **parent Application** owns its registered child Applications. Parents locate and control children; children receive the collaborators they need explicitly. The Application at the top of that hierarchy is its **root Application**. For state, **borrowed** and **owned** describe who is responsible for disposal: - A supplied or declared `state` is borrowed. Destroying an owner releases that owner's subscriptions and leaves the source available to other users. - A `createState()` result is owned. Destroying the owner releases its subscriptions, then calls the selected StateApi's optional `disposeOwned()`. A **cleanup function** releases a subscription or other resource. **Idempotent** means repeated calls have the same effect as one call. Adapters must return idempotent subscription cleanup functions; core does not wrap each returned cleanup to establish that property. ## Default and isolated runtimes The named exports from `marionette` belong to the **default runtime**. `createMarionette()` returns an **isolated runtime** with its own classes, adapter and renderer configuration, and Radio channels. Choose one runtime's classes and setters when composing that part of the application. See [Runtime isolation](/docs/runtime-isolation.md). A state source created for one owner is still an owned state source; it does not create another runtime. Current package imports use `marionette`; historical migration guides may refer to the old `backbone.marionette` package name. ## Application lifecycle and readiness `start()`, `stop()`, `restart()`, and `destroy()` are Application **lifecycle operations**. A **readiness hook** is one of `onBeforeStart`, `onBeforeStop`, or `onBeforeDestroy`. Marionette awaits a Promise returned by one of those hooks before completing that phase. The corresponding `before:*` event listeners are synchronous notifications; their return values are not awaited. `onStart`, `onStop`, `onDestroy`, and their matching events are **completion notifications** and are not awaited either. See [Application lifecycle](/docs/application.md) for ordering, cancellation, and the readiness `AbortSignal`. [Canonical source](/docs/markdown/docs/terminology.md) · [Source identity](/docs/manifest.json) --- Document: docs/agent-tools.md Canonical URL: https://marionettejs.com/docs/agent-tools/ Markdown URL: https://marionettejs.com/docs/agent-tools.md Reading SHA-256: 84ebeff9b9ed3660c3aa94a245ce5cf2ee82a981982ed802b133dcb86e2b1e92 # Set up an agent Use the installed package's documentation and a small application instruction file first. The optional Marionette skill helps an agent select those documents and apply their lifecycle and integration rules. None of these resources requires an account, network access, hosted model, or shared API key to read. ## Install the consumer skill Builds containing these resources ship `dist/agent-skill/` and `dist/docs/` inside the `marionette` package. Check that both exist in your installed package before following these steps; earlier artifacts do not contain them. Do not upgrade an application just to install instructions. Copy the whole `dist/agent-skill/` directory, including `scripts/`, into the skill location supported by your agent client, naming the copied folder `marionette`. Use the client's documented installation mechanism; installing an npm dependency does not automatically activate an agent skill. For a source checkout, the same skill lives in `skills/marionette/`. Use the checkout matching the package's known source revision. For a client configured to read project skills from `.agents/skills`, run this from your application directory when that destination does not already exist: ```sh mkdir -p .agents/skills cp -R node_modules/marionette/dist/agent-skill .agents/skills/marionette ``` Adapt the source path for a hoisted dependency or package manager without `node_modules`. When updating an existing copy, review its local changes and replace it deliberately; do not create nested copies. Keep the skill in the application's repository if the team should share it. Update it alongside the package, reviewing any project-specific edits. Agent clients differ in discovery and reload behavior; follow the client's setup instructions and confirm that it lists `marionette` before relying on automatic selection. In a client supporting named skill invocation, try: ```text Use $marionette to inspect this application's installed version and integrations. Find the matching routing guide and explain which component owns cancellation. Do not change the application yet. ``` A successful activation identifies the installed package, reports its documentation revision, reads the relevant page, and distinguishes the router from Marionette's lifecycle. A response that only repeats the prompt has not demonstrated retrieval. If the client cannot load skills, give it [Build with Marionette](/docs/agents.md) and the matching task guide directly; the skill is an optional entry point. ## Read matching docs locally The skill bundles a read-only helper requiring Node 24 or later. It addresses a specific retrieval problem: the copied skill must locate the application's installed docs, including hoisted dependencies, without importing application code. It does not add a server, registry, or production dependency. ```sh node .agents/skills/marionette/scripts/docs.mjs --project . --list node .agents/skills/marionette/scripts/docs.mjs --project . --page docs/routing.md ``` `--list` returns JSON with absolute page paths, version, source revision, local change status, and content digest. `--page` accepts an exact `source` path from that list and prints one provenance record followed by the page's Markdown. Run from the application workspace, not a neighboring package with a different Marionette dependency. `--project` defaults to the current directory. For a package manager without a physical `node_modules` tree, find that application's physical package directory using its package manager and supply `--package-root /path/to/marionette`. The helper does not execute resolver hooks or install packages to guess that path. Exit status `1` indicates missing docs, invalid arguments, a version mismatch, or inconsistent files; it does not silently switch to a different source. The helper validates documentation hashes and their package version. This proves that the files agree with their manifest, not that an arbitrary custom runtime was built from that revision. Check installed exports and test uncertain behavior. For local builds, the version alone cannot identify a source commit; `sourceDirty: true` means local changes are included. Older packages without docs require an exact release or known source checkout, not an automatic fallback to today's website. ## Record the application decisions Adapt the [application instruction template](/docs/application-agent-template.md). Record actual integration choices, initialization points, resource owners, and working test commands. Keep those decisions in the application. The library's maintainer `AGENTS.md` describes changing Marionette itself and should not be copied into a consumer application. ## Choose an optional service only for a specific need | Resource | Useful for | Boundary | | --- | --- | --- | | Packaged Markdown and manifest | Reading the contract shipped with an installed package | Available offline; verify custom runtime provenance separately. | | Website Markdown and `llms.txt` | Discovering pages and reading a published snapshot | An index is a set of links, not automatic instruction installation. Check version and source metadata. | | Context7 | Finding relevant excerpts through a supported agent integration | Optional third-party retrieval; results can omit setup or mix versions. Verify against the exact source. | | Local skill helper | Finding and checking packaged docs from a consumer workspace | Reads files only; no network, project-code execution, or automatic fallback. | | Website WebMCP tools | Operating the website's interactive example | Controls that example, not the consumer application. It is not a remote documentation server. | For Context7, use the public `marionettejs/marionette` library and the client's Context7 setup instructions. Each developer uses their own account and limits. Do not put a maintainer's API key in a website, repository, or shared public proxy. If a free quota is exhausted, read the static or installed docs directly; do not enable paid overages. Check the current [Context7 plans](https://context7.com/plans) and [documentation](https://context7.com/docs) before configuring an account. Public indexing does not prove that the latest source configuration is active. Marionette does not require a custom MCP server, a hosted AI chat, or a WebMCP connection to build an application. A future local MCP wrapper would need to solve a demonstrated client integration gap beyond reading these files. Keep tooling outside the production import graph and avoid duplicating the contract in tool prompts. The same documentation remains available to human readers. [Canonical source](/docs/markdown/docs/agent-tools.md) · [Source identity](/docs/manifest.json) --- Document: docs/application-agent-template.md Canonical URL: https://marionettejs.com/docs/application-agent-template/ Markdown URL: https://marionettejs.com/docs/application-agent-template.md Reading SHA-256: 97316b5362ca10cd602e4274854b9db9f080d89854fd758bb5c028f227245021 # Record an application's agent instructions Use this template to record decisions an agent cannot safely infer from Marionette alone. It belongs in the application repository's instruction file, usually `AGENTS.md` when supported by the agent client. Merge it with existing instructions instead of replacing unrelated project policy. Fill each field from the installed package, lockfile, configuration, and actual test scripts. Delete irrelevant fields. A question still being decided should be marked unresolved, with the constraint that blocks the decision; do not turn a placeholder into an invented default. Never put credentials or private customer data in these instructions. ```markdown # Marionette application context ## Installed contract - Application workspace: [directory containing this application's manifest]. - Marionette package/version and install source: [lockfile and resolved package]. - Documentation: [installed dist/docs path or exact release/source snapshot]. - Source revision and local changes, when known: [manifest provenance]. - Optional Marionette packages: [actual versions, or none]. Use matching documentation. Check the installed exports before adopting an API from an external example. Do not change dependency versions to make a snippet fit. ## Integration decisions - Runtime and registration point: [actual module; shared or isolated and why]. - Renderer/templates: [actual choice and setup module]. - Data sources and DataApi: [actual choice, observability, registration or default]. - State sources and StateApi: [actual choice, ownership, registration or default]. - DomApi and EventDelegator: [actual choices or defaults]. - Router: [actual library or none; URL/history owner]. - Navigation/loading: [controller or feature owner; stale-result policy]. Preserve compatible established choices. Select these capabilities independently; a router choice does not imply a data, state, renderer, or DOM adapter change. ## Ownership and verification - Root mount and View/Region owner: [actual entry point]. - Shared resources and disposal owners: [actual subscriptions/state/widgets]. - Unit/component check: [existing command and working directory]. - Browser interaction check: [existing command and working directory]. - Build/type check: [existing command and working directory]. - Relevant existing patterns: [a few actual source or test paths]. For the changed behavior, verify the appropriate interaction and cleanup boundary. Report the checks actually run and anything left untested. Update this file when an application decision changes; keep the API reference in the matching docs. ``` Keep the completed file short. Link to substantial project architecture or test guides rather than copying them. The purpose is to preserve the application's choices across tasks, not to prescribe a new router, test runner, or framework. For skill installation and optional services, see [Set up an agent](/docs/agent-tools.md). [Canonical source](/docs/markdown/docs/application-agent-template.md) · [Source identity](/docs/manifest.json) --- Document: docs/marionette.view.md Canonical URL: https://marionettejs.com/docs/view/ Markdown URL: https://marionettejs.com/docs/view.md Reading SHA-256: fa47943dac17b3812086bb370caef231c6c4ae13552a53583eb1f0d8b3c0b6f8 # Marionette.View A `View` manages one part of a screen: its content, DOM interactions, and child views. Give it a template and data, and it renders into a root element, `el`. Plain objects and native DOM methods work by default. Use named [Regions](/docs/region.md) to give child views a place within that element, and [Behaviors](/docs/behavior.md) to share interaction logic across views. `View` includes: - [The DOM API](/docs/dom-api.md) - [Class Events](/docs/class-events.md#view-events) - [DOM Interactions](/docs/dom-interactions.md) - [Child Event Bubbling](/docs/events.md#event-bubbling) - [Entity Events](/docs/entity-events.md) - [View Rendering](/docs/rendering.md) - [Prerendered Content](/docs/prerendered-dom.md) - [View Lifecycle](/docs/lifecycle.md) A `View` can have [`Region`s](/docs/region.md) and [`Behavior`s](/docs/behavior.md) ## Documentation Index * [Instantiating a View](#instantiating-a-view) * [Method results and side effects](#method-results-and-side-effects) * [Rendering a View](#rendering-a-view) * [Using a View Without a Template](#using-a-view-without-a-template) * [Refreshing Root Attributes](#refreshing-root-attributes) * [View Lifecycle and Events](#view-lifecycle-and-events) * [Entity Events](#entity-events) * [DOM Interactions](#dom-interactions) * [Behaviors](#behaviors) * [Managing Children](#managing-children) * [Laying Out Views - Regions](#laying-out-views---regions) * [Showing a Child View](#showing-a-child-view) * [Accessing a Child View](#accessing-a-child-view) * [Detaching a Child View](#detaching-a-child-view) * [Destroying a Child View](#destroying-a-child-view) * [Region Availability](#region-availability) * [Efficient Nested View Structures](#efficient-nested-view-structures) * [Listening to Events on Children](#listening-to-events-on-children) ## Instantiating a View When instantiating a `View` there are several properties, if passed, that will be attached directly to the instance: `attributes`, `behaviors`, `childViewEventPrefix`, `childViewEvents`, `childViewTriggers`, `className`, `collection`, `collectionEvents`, `el`, `events`, `id`, `model`, `modelEvents`, `regionClass`, `regions`, `stateEvents`, `tagName`, `template`, `templateContext`, `triggers`, `ui` ```javascript import { View } from 'marionette'; const myView = new View({ template: () => '

Content

' }); ``` These properties are defined by Marionette's standalone `View` constructor. When Marionette creates the View's element, it copies own enumerable `attributes` properties, including symbols. The default DomApi applies string attribute names only; inherited and non-enumerable properties are not copied. When applied, `id` and `className` assignments occur afterward and override the corresponding `attributes` keys. See the [`DomApi.setAttributes` contract](/docs/dom-api.md#setattributesel-attrs). ## Method results and side effects These operations run synchronously. Use lifecycle hooks for additional work; returning a Promise from a View hook does not delay rendering or destruction. | Method | Result | Effect | | --- | --- | --- | | `render()` | This View | Evaluates the template, updates contents and UI bindings. Rendering again resets its Regions and destroys their current children. `template: false` and a destroyed View make this a no-op. | | `renderAttributes()` | This View | Refreshes root attributes without rendering contents or recreating children. | | `destroy(options)` | This View | Removes the root element, destroys owned Regions/children and Behaviors, releases subscriptions and owned State. Repeated destruction is a no-op. | | `isRendered()`, `isAttached()`, `isDestroyed()` | Boolean | Read lifecycle state without rendering. Attachment is Marionette's tracked state; see [monitoring](/docs/lifecycle.md). | | `hasRegion(name)`, `getRegion(name)` | Boolean or Region/`undefined` | Read a named registration without rendering the parent. | | `getRegions()` | New name-to-Region object | Read registrations; changing this object does not change ownership. | | `showChildView(name, view, options)` | Supplied child View | Renders the parent if needed, then delegates to the named Region. The result alone does not establish adoption when `allowMissingEl` permits a missing mount. | | `getChildView(name)` | Current child or `undefined` | Renders the parent if needed before reading the named Region. | | `detachChildView(name)` | Detached child or `undefined` | Renders the parent if needed, then transfers a live child to the caller. | | `addRegion(name, definition)` | Registered Region | Constructs or registers a Region without rendering the parent. | | `addRegions(definitions)` | Map of added Regions, or `undefined` for no entries | Registers the batch; see [ownership constraints](/docs/region.md#reading-region-ownership). | | `removeRegion(name)` | Removed Region | Destroys that Region and its current child. | | `removeRegions()` | Map of removed Regions | Destroys every registered Region and its current child. | | `emptyRegions()` | Map of Regions | Renders the parent if needed, destroys current children, and keeps the Regions available. | `getChildView`, `showChildView`, `detachChildView`, and `removeRegion` require a registered name and throw [`MN0020`](/errors/MN0020.md) when it is absent. `getRegion` returns `undefined` for an absent valid name. Region names must be non-empty strings; an empty string throws [`MN0032`](/errors/MN0032.md). A supplied `state` is borrowed rather than copied as a normal constructor option. See [State ownership](/docs/state.md#borrowed-and-owned-sources) for `getState()`, `createState()`, subscriptions, and disposal. ## Rendering a View The Marionette View implements a powerful render method which, given a [`template`](/docs/rendering.md#setting-a-view-template), will build your HTML from that template, mixing in `model` or `collection` data and any extra [template context](/docs/rendering.md#adding-context-data). Marionette `View` defines `render`, and this method should not be overridden. To add functionality around rendering, use the [`render` and `before:render` events](/docs/class-events.md#render-and-beforerender-events). For more detail on how to render templates, see [View Template Rendering](/docs/rendering.md). ### Using a View Without a Template With [`template: false`](/docs/rendering.md#using-a-view-without-a-template), `render()` returns the View without changing its contents or running `before:render` and `render`. Other View events and DOM interactions remain available. Use this for [`prerendered content`](/docs/prerendered-dom.md) that the View should preserve. ### Refreshing Root Attributes `renderAttributes()` reevaluates a View's declarative `attributes`, `className`, and `id`, then applies those values to its existing root element. The method is also available on `CollectionView`. ```javascript import { View } from 'marionette'; const SelectableRow = View.extend({ tagName: 'tr', attributes() { return { 'aria-selected': this.isSelected ? 'true' : 'false' }; }, className() { return this.isSelected ? 'danger' : null; }, template: false, setSelected(isSelected) { this.isSelected = isSelected; return this.renderAttributes(); } }); const row = new SelectableRow(); const rootElement = row.el; row.setSelected(true); export { rootElement, row }; ``` With the default DomApi, only an explicit `null` removes an attribute. An `undefined` value or omitted key leaves the existing attribute untouched; Marionette does not retain the names returned by an earlier call. Other values, including `false`, `0`, and an empty string, use the browser's attribute string conversion. For boolean HTML attributes, declare `disabled: isDisabled ? '' : null`; `disabled: false` still creates a present attribute and disables the element. `id` and `className` continue to override matching keys from `attributes` when they are declared. Live form properties such as `input.value` and `input.checked` should be updated explicitly, separately from their default-value attributes. Use `className` as the View-level class declaration, as shown above. The `attributes` map continues to use raw DOM attribute names for lower-level cases. Marionette normalizes the View declaration to the `class` attribute before calling the DomApi, including for a supplied SVG root. `renderAttributes()` returns the View. It does not call the template, emit the render lifecycle, replace the root element, rebind `ui` or DOM events, or reset Regions. It is not called automatically by `render()`. Calls after destruction begins are no-ops and do not resolve the attribute declarations. When a View uses a supplied `el`, construction still leaves that element's attributes unchanged. A later `renderAttributes()` call applies only the keys in the current declaration, so unrelated host attributes remain caller-owned. ## View Lifecycle and Events An instantiated `View` is aware of its lifecycle state and will throw events related to when that state changes. The view states indicate whether the view is rendered, attached to the DOM, or destroyed. Read More: - [View Lifecycle](/docs/lifecycle.md) - [View DOM Change Events](/docs/class-events.md#dom-change-events) - [View Destroy Events](/docs/class-events.md#destroy-events) ## Entity Events A `View` subscribes to its `model` and `collection` through the configured [DataApi](/docs/data-api.md). Event names and callback arguments belong to that data provider. Plain objects and arrays do not emit changes; declaring entity event maps for unobservable values throws `MN0037`. Read More: - [Entity Events](/docs/entity-events.md) ## DOM Interactions `View` provides `events`, `triggers`, and `ui` for DOM interactions. Read More: - [DOM Interactions](/docs/dom-interactions.md) ## Behaviors A `Behavior` provides a clean separation of concerns to your view logic, allowing you to share common user-facing operations between your views. Read More: - [Using `Behavior`s](/docs/behavior.md#using-behaviors) ## Managing Children `View` provides a simple interface for managing child-views with [`showChildView`](#showing-a-child-view), [`getChildView`](#accessing-a-child-view), and [`detachChildView`](#detaching-a-child-view). These methods all access `regions` within the view. We will cover this here but for more advanced information, see the [documentation for regions](/docs/region.md). ### Laying Out Views - Regions The `View` class lets us manage a hierarchy of views using `regions`. Regions are a hook point that lets us show views inside views, manage the show/hide lifecycles, and act on events inside the children. **This Section only covers the basics. For more information on regions, see the [Regions Documentation.](/docs/region.md)** Regions are ideal for rendering application layouts by isolating concerns inside another view. This is especially useful for independently re-rendering chunks of your application without having to completely re-draw the entire screen every time some data is updated. Regions can be added to a View at class definition, with [`regions`](/docs/region.md#defining-regions), or at runtime using [`addRegion`](/docs/region.md#adding-regions). When you extend `View`, we use the `regions` attribute to point to the selector where the new view will be displayed: ```javascript import _ from 'underscore'; import { View } from 'marionette'; const MyView = View.extend({ template: _.template(`
`), regions: { firstRegion: '#first-region', secondRegion: '#second-region' } }); ``` When we show views in the region, the contents of `#first-region` and `#second-region` will be replaced with the root element of the child View we show. The string values in this example are CSS selectors scoped to the `View`'s `el`. ### Showing a Child View To show a view inside a region, simply call `showChildView(regionName, view)`. This will handle rendering the view's HTML and attaching it to the DOM for you: ```javascript import { View } from 'marionette'; const ChildView = View.extend({ template() { return '

Content

'; } }); const ParentView = View.extend({ template() { return `
`; }, regions: { firstRegion: '.first-region', secondRegion: '.second-region' } }); export function runViewChildRegionLifecycle() { const parentView = new ParentView(); parentView.showChildView('firstRegion', new ChildView()); const childView = parentView.getChildView('firstRegion'); parentView.detachChildView('firstRegion'); parentView.showChildView('secondRegion', childView); parentView.getRegion('secondRegion').empty(); return parentView; } ``` Note: If `view.showChildView(region, subView)` is invoked before the `view` has been rendered, it will automatically render the `view` so the Region's `el` exists within the parent root; the root may still be detached. ### Accessing a Child View To access the child view of a `View` - use the `getChildView(regionName)` method. This will return the view instance that is currently being displayed at that region. The example gets the exact `ChildView` shown in `firstRegion` before moving it. If the named Region exists but has no current View, `getChildView` returns `undefined`. ### Detaching a Child View You can detach a child view from a Region through `detachChildView(regionName)`. It returns the same live, rendered View so that it can be shown again without rendering a second time. In the example, the parent detaches its child from `firstRegion` before showing that same child in `secondRegion`. This is a proxy for [Region `detachView()`](/docs/region.md#detaching-existing-views). ### Destroying a Child View To destroy and clear a child owned by a View, empty its owning Region. The example calls `parentView.getRegion('secondRegion').empty()`, which destroys the current child and leaves `secondRegion` empty and available for another View. ### Region Availability Defined regions are registered during `View` construction. `hasRegion(name)`, `getRegion(name)`, and `getRegions()` query the View's own Region registry without rendering, including when the View is unrendered or destroyed. `getRegions()` returns a fresh, safe own-key snapshot. Child View operations such as `showChildView`, `detachChildView`, and `getChildView` still render a live, unrendered View before dispatching through any `getRegion` override. `emptyRegions()` likewise renders before calling the overridable `getRegions()` and emptying its returned snapshot. Calling `getRegion(name)` does not render the parent or resolve the Region element. Calling the returned Region's `show(view)` resolves its element but does not render the parent. Use `showChildView`, or render the parent first, when showing a child into a declared selector Region. `getRegion(name)` and `hasRegion(name)` support optional lookup: an unknown name returns `undefined` or `false`, respectively. Operations that require a Region — `showChildView`, `detachChildView`, `getChildView`, and `removeRegion` — throw a `RegionError` with code [`MN0020`](/errors/MN0020.md) when the named Region does not exist. Region names must be non-empty strings. The public types require strings; an empty name throws a `RegionError` with code [`MN0032`](/errors/MN0032.md). Child View operations reject empty names before rendering the parent. ## Efficient Nested View Structures Show a parent's Region children in `onRender` when they should be recreated with that parent's template. During initial display, this builds the nested View tree before the owning Region attaches the parent. Keep independently editable content in child Views and update those children without re-rendering the parent when their state must survive. ```javascript import { View } from 'marionette'; const ParentView = View.extend({ // ... onRender() { this.showChildView('header', new HeaderView()); this.showChildView('footer', new FooterView()); } }); myRegion.show(new ParentView()); ``` Child Views can show their own Region children in `onRender` too. Marionette coordinates the render and attachment lifecycles; browser layout and paint counts depend on the DOM, styles, and application callbacks. Measure those costs in the running application when they matter. ## Listening to Events on Children Using regions lets you listen to the events that fire on child views - views attached inside a region. This lets a parent view take action depending on what events are triggered in views it directly owns. Read More: - [Child Event Bubbling](/docs/events.md#event-bubbling) [Canonical source](/docs/markdown/docs/marionette.view.md) · [Source identity](/docs/manifest.json) --- Document: docs/marionette.region.md Canonical URL: https://marionettejs.com/docs/region/ Markdown URL: https://marionettejs.com/docs/region.md Reading SHA-256: fc4d0668c1d52763debb29380efbdadb42c3f989d351314e3cb3fd4dfc97b3c7 # Marionette.Region A `Region` gives a changing part of the screen a place to live. Show a view, replace it with another, or empty the Region when that part of the interface is no longer needed. By default, replacing or emptying a view destroys it; the Region remains available for the next view. `Region` includes: - [Common Marionette Functionality](/docs/common.md) - [Class Events](/docs/class-events.md#region-events) - [The DOM API](/docs/dom-api.md) See the documentation for [laying out views](/docs/view.md#laying-out-views---regions) for an introduction in managing regions throughout your application. Regions maintain the [View's lifecycle](/docs/lifecycle.md) while showing or emptying a view. ## Documentation Index * [Instantiating a Region](#instantiating-a-region) * [Reading Region ownership](#reading-region-ownership) * [Lifecycle transition contract](#lifecycle-transition-contract) * [Defining the Application Region](#defining-the-application-region) * [Defining Regions](#defining-regions) * [String Selector](#string-selector) * [Additional Options](#additional-options) * [Specifying `regions` as a Function](#specifying-regions-as-a-function) * [Using a RegionClass](#using-a-regionclass) * [Referencing UI in `regions`](#referencing-ui-in-regions) * [Adding Regions](#adding-regions) * [Removing Regions](#removing-regions) * [Using Regions on a view](#using-regions-on-a-view) * [Showing a View](#showing-a-view) * [Checking whether a region is showing a view](#checking-whether-a-region-is-showing-a-view) * [Wrapping a non-Marionette view](#wrapping-a-non-marionette-view) * [Emptying a Region](#emptying-a-region) * [Preserving Existing Views](#preserving-existing-views) * [Detaching Existing Views](#detaching-existing-views) * [`reset` A Region](#reset-a-region) * [`destroy` A Region](#destroy-a-region) * [Check If View Is Being Swapped By Another](#check-if-view-is-being-swapped-by-another) * [Set How View's `el` Is Attached and Detached](#set-how-views-el-is-attached-and-detached) * [Configure How To Remove View](#configure-how-to-remove-view) ## Instantiating a Region A `Region` accepts `el`, `parentEl`, `allowMissingEl`, and `replaceElement`. `el` is a native element or a selector; selector resolution is deferred until an operation needs the element. `parentEl` limits selector lookup and may be an element, document, or function returning one. `allowMissingEl` and `replaceElement` may also be functions; a boolean supplied to `show(view, options)` overrides the corresponding Region setting for that call. ```javascript import { Region } from 'marionette'; const myRegion = new Region({ el: '#content' }); ``` While regions may be instantiated and useful on their own, their primary use case is through the [`Application`](#defining-the-application-region) and [`View`](#defining-regions) classes. ## Reading Region ownership A Region registered on a View exposes that existing relationship through pure, read-only queries. `getOwner()` returns the owning View and `getName()` returns the Region's name within that View. Neither query renders the View, resolves the Region element, or changes ownership. A standalone Region returns `undefined` from both methods. Removing a registered Region or completing its destruction clears both values. A throwing lifecycle hook interrupts teardown without rolling back ownership or retrying destruction. A Region has one authoritative registration. Re-adding that same Region instance under its current owner and name returns it without lifecycle events or ownership changes. Registering it under a different owner or name, registering a Region whose destruction has begun or completed, or replacing an occupied Region name through `addRegion` throws [`MN0030`](/errors/MN0030.md) before committing the conflicting registration. A conflict found before `addRegions` starts rejects the whole batch. Lifecycle hooks must not re-register the Region or occupy its registration name while registration is in progress. Failed batch registration is not rolled back. Remove an existing named Region before replacing it, and use a fresh Region instance when another View needs a Region. ```javascript const contentRegion = myView.getRegion('content'); contentRegion.getOwner() === myView; // true contentRegion.getName(); // 'content' ``` ## Lifecycle transition contract A Region owns at most one current View. Its public lifecycle state can be read without changing it: | State | `hasView()` | `isDestroyed()` | `currentView` | | --- | --- | --- | --- | | Empty | `false` | `false` | `undefined` | | Occupied | `true` | `false` | The View shown by the Region | | Destroyed | `false` | `true` | `undefined` | `isSwappingView()` is a temporary operation flag rather than a fourth stable state. It is `true` while one occupied Region replaces its current View with another, including the Region's `before:show`, `before:empty`, `empty`, and `show` callbacks. It returns to `false` when `show` completes. `isReplaced()` independently reports whether `replaceElement` has temporarily replaced the Region element; it does not change which lifecycle operations are valid. | Operation | Empty Region | Occupied Region | Destroyed Region | | --- | --- | --- | --- | | `show(view)` when the Region element resolves | Renders the View if needed, shows it, and enters occupied. | Showing the same View is a no-op. Showing a different View destroys the old View and swaps to the new one. | Returns the Region without inspecting or changing the caller-owned View or resolving the element. | | `detachView()` | Returns `undefined`; state is unchanged. | Detaches and returns the live View, then enters empty. | Returns `undefined` without changing state or DOM or emitting lifecycle events. | | `empty()` | Returns the Region and, when its element resolves, removes unmanaged contents from that element. | Destroys the current View, clears `currentView`, and enters empty. | Returns the Region without resolving the element or changing lifecycle state or DOM. | | `reset()` | Empties the Region and resets its element reference. | Destroys the current View, enters empty, and resets the element reference. | Returns the Region without resolving the element or changing lifecycle state, DOM, or element caches. | | Current View is destroyed externally | No effect. | Runs the Region's empty lifecycle once, clears `currentView`, and enters empty. | No effect. | | `destroy()` | Runs the destroy lifecycle and enters destroyed. | Emits `before:destroy`, destroys and empties the current View, enters destroyed, then emits `destroy`. | Returns the Region without repeating cleanup or lifecycle events. | Successful `show`, `empty`, and `destroy` calls return the Region when their operation completes. With `allowMissingEl: true`, `show` instead returns `undefined` and leaves the current View unchanged when its element does not resolve. A View returned by `detachView()` remains the caller's responsibility until the same or another Region shows it or it is destroyed. After destruction, `show()`, `empty()`, and `reset()` return the Region without changing it, and `detachView()` returns `undefined`. As soon as destruction begins, `show()`, `detachView()`, and recursive `destroy()` calls are no-ops. `empty()` and `reset()` remain available during cleanup. A View passed to `show()` during or after destruction remains caller-owned and unchanged. A destroyed Region cannot be reused. When its current View destroys itself, the Region clears that View's ownership and releases the owning parent View's subscriptions to it. Later events on the destroyed child are no longer forwarded to the parent. The following example preserves a View by detaching it before showing it again. Calling `empty()` afterward destroys the View and returns the Region to its empty state. ```javascript import { Region, View } from 'marionette'; export function runRegionLifecycle() { const region = new Region({ el: '#content' }); const contentView = new View({ template() { return '

Content

'; } }); region.show(contentView); const detachedView = region.detachView(); region.show(detachedView); region.empty(); return region; } ``` ## Defining the Application Region The Application defines a single region `el` using the `region` attribute. This can be accessed through `getRegion()` or have a view displayed directly with `showView()`. Below is a short example: ```javascript import { Application } from 'marionette'; import SomeView from './view'; const MyApp = Application.extend({ region: '#main-content', onStart() { const mainRegion = this.getRegion(); // Has all the properties of a `Region` mainRegion.show(new SomeView()); } }); ``` For more information, see the [Application docs](/docs/application.md#application-region). ## Defining Regions In Marionette you can define a region with a string selector or an object literal on your `Application` or `View`. This section will document the two types as applied to `View`, although they will work for `Application` as well - just replace `regions` with `region` in your definition. Region declaration maps, including maps passed to `addRegions`, use own enumerable string keys in standard JavaScript own-key order. Inherited, symbol, and non-enumerable properties are ignored, and a numeric `length` property is an ordinary Region name rather than an array-like signal. Arrays, sparse arrays, and other array-like values are not supported as Region declaration maps. Named View Region operations require a non-empty string name. `addRegion`, `removeRegion`, `hasRegion`, `getRegion`, `showChildView`, `detachChildView`, and `getChildView` throw [`MN0032`](/errors/MN0032.md) for an empty name. The public types require strings; unsupported shapes have no guaranteed diagnostic. Ordinary collision names such as `constructor`, `toString`, and `__proto__` remain valid when explicitly registered. ### String Selector You can use a CSS selector string to define regions. ```javascript import { View } from 'marionette'; const MyView = View.extend({ regions: { mainRegion: '#main' } }); ``` `Region#getEl(selector)` resolves the selector within `parentEl`, or within the document when no parent is defined, and returns the first matching native DOM element. A custom `getEl` override must preserve that native-element return contract; do not return a `NodeList` or jQuery collection. To customize selector lookup through the DOM adapter, implement `findEl(context, selector)` instead. The v4 `DomApi#getEl` method is not part of the v5 DOM API. Selector lookup is deferred until a DOM operation such as `show()` needs it. During construction, `initialize` observes the configured selector string in `this.el`; constructing a Region does not query the document or dispatch through a `getEl` override. ### Additional Options You can define regions with an object literal. Object literal definitions expect an `el` property - the selector string to hook the region into. With this format is possible to define whether showing the region overwrites the `el` or just overwrites the content (the default behavior). Region defaults and object-literal definitions contribute their own enumerable properties, including symbols, through object spread. Inherited and non-enumerable properties are ignored when Marionette builds the Region options. To replace the Region's placeholder with the child View's root element, use `replaceElement: true`: ```javascript import { View } from 'marionette'; const ReplacementView = View.extend({ className: 'new-class', template: () => '

Replacement content

' }); const Layout = View.extend({ template: () => '
', regions: { main: { el: '.overwrite-me', replaceElement: true } } }); export const view = new Layout().render(); export const placeholder = view.el.querySelector('.overwrite-me'); export const replacement = new ReplacementView(); // Rendering the parent creates the placeholder. Showing the child replaces it. view.showChildView('main', replacement); view.$('.overwrite-me').length; // 0 view.$('.new-class').length; // 1 ``` `showChildView()` replaces `.overwrite-me` with the child's `el`; rendering the parent alone does not. The `className` option takes a class name, without the `.` used in CSS selectors. Emptying the Region destroys its current child and restores the original placeholder. The parent View's own root remains unchanged. This is useful when a container requires particular direct children, such as a `table` body containing rows. Choose a child `tagName` valid for that container. ```js import { View } from 'marionette'; const MyView = View.extend({ regions: { regionDefinition: { el: '.bar', replaceElement: true } } }); ``` **Errors** An operation that needs the element throws `MN0004` when no `el` is configured, or `MN0005` when a selector finds no element and `allowMissingEl` is false. Construction alone does not resolve the selector. ### Specifying `regions` as a Function On a `View` the `regions` attribute can also be a [function returning an object](/docs/basics.md#functions-returning-values): ```javascript import { View } from 'marionette'; const MyView = View.extend({ regions(){ return { firstRegion: '#first-region' }; } }); ``` ### Using a RegionClass If you've created a custom region class, you can use it to define your region. ```javascript import { Application, Region, View } from 'marionette'; const MyRegion = Region.extend({ onShow(){ // Scroll to the middle const viewHeight = this.currentView.el.getBoundingClientRect().height; const regionHeight = this.el.getBoundingClientRect().height; this.el.scrollTop = viewHeight / 2 - regionHeight / 2; } }); const MyApp = Application.extend({ regionClass: MyRegion, region: '#first-region' }) const MyView = View.extend({ regionClass: MyRegion, regions: { firstRegion: { el: '#first-region', regionClass: Region // Don't scroll this to the top }, secondRegion: '#second-region' } }); ``` ### Referencing UI in `regions` The UI attribute can be useful when setting region selectors - simply use the `@ui.` prefix: ```javascript import { View } from 'marionette'; const MyView = View.extend({ ui: { region: '#first-region' }, regions: { firstRegion: '@ui.region' } }); ``` ## Adding Regions To add regions to a view after it has been instantiated, simply use the `addRegion` method: ```javascript import MyView from './myview'; const myView = new MyView(); myView.addRegion('thirdRegion', '#third-region'); ``` Now we can access `thirdRegion` as we would the others. You can also add multiple regions using `addRegions`. ```javascript import MyView from './myview'; const myView = new MyView(); myView.addRegions({ main: { el: '.overwrite-me', replaceElement: true }, sidebar: '.sidebar' }); ``` ## Removing Regions You can remove all of the regions from a view by calling `removeRegions` or you can remove a region by name using `removeRegion`. When a region is removed the region will be destroyed. ```javascript import { View } from 'marionette'; const MyView = View.extend({ regions: { main: '.main', sidebar: '.sidebar', header: '.header' } }); const myView = new MyView(); // remove only the main region const mainRegion = myView.removeRegion('main'); mainRegion.isDestroyed(); // -> true // remove all regions myView.removeRegions(); ``` ## Using Regions on a view In addition to adding and removing regions there are a few methods to help utilize regions. `hasRegion` and `getRegion` are pure own-registry queries, and `getRegions` returns a pure snapshot; none renders. Child View operations and `emptyRegions` first render a live, unrendered View before resolving or mutating Regions. - `getRegion(name)` - Request an own registered Region without rendering. - `getRegions()` - Return a fresh own-key snapshot of registered Regions without rendering. - `hasRegion(name)` - Check if a View has an own registered Region without rendering. - `emptyRegions()` - Render when needed, then empty all Regions returned by `getRegions()`. ## Showing a View Once a region is defined, you can call its `show` method to display the view: ```javascript const myView = new MyView(); const childView = new MyChildView(); myView.render(); const mainRegion = myView.getRegion('main'); // render and display the child View mainRegion.show(childView, { fooOption: 'bar' }); ``` The parent View must already be rendered before calling a selector Region's `show` directly. Use `showChildView('main', childView)` to render the parent when needed before showing the child. This is equivalent to a view's `showChildView` which can be used as: ```javascript const myView = new MyView(); const childView = new MyChildView(); // render and display the view myView.showChildView('main', childView, { fooOption: 'bar' }); ``` Both forms require a Marionette View instance. Construct a `View` explicitly when displaying a template or static content; Regions do not allocate hidden Views from View classes, functions, strings, or option objects. The [wrapper pattern](#wrapping-a-non-marionette-view) provides explicit ownership for legacy integrations. ```javascript import { View } from 'marionette'; myView.showChildView('header', new View({ template: () => 'Welcome to the site' })); ``` The argument after the View instance in `Region#show(view, options)` and `View#showChildView(name, view, options)` is a separate show-options object passed to the [events fired during `show`](/docs/class-events.md#show-and-beforeshow-events). For more information on `showChildView` and `getChildView`, see the [Documentation for Views](/docs/view.md#managing-children) **Errors** - A destroyed View throws `MN0007`. Other input shapes are unsupported; core does not guarantee a Marionette diagnostic for an invalid value. - An error will be thrown if the view is already managed by a Region or CollectionView, including a filtered or deferred CollectionView child. Detach it from that owner first. ### Checking whether a region is showing a view If you wish to check whether a region has a view, you can use the `hasView` function. This will return a boolean value depending whether or not the region is showing a view. ```javascript const myView = new MyView(); myView.render(); const mainRegion = myView.getRegion('main'); mainRegion.hasView() // false mainRegion.show(new OtherView()); mainRegion.hasView() // true ``` If you show a view in a region with an existing view, Marionette will [remove the existing View](#emptying-a-region) before showing the new one. ### Wrapping a non-Marionette view Regions and CollectionViews manage Marionette Views. They do not synthesize render or destroy events for Backbone Views or fall back to a `remove()` method. Keep a legacy integration inside a Marionette owner: ```javascript import { View } from 'marionette'; import LegacyView from './legacy-view.js'; const LegacyWrapper = View.extend({ template: () => '
', onRender() { this.legacy?.remove(); this.legacy = new LegacyView({ el: this.$('.legacy')[0] }); this.legacy.render(); }, onDestroy() { this.legacy?.remove(); } }); ``` Show `new LegacyWrapper()` in the Region. The wrapper owns the legacy instance and translates its actual rendering and cleanup API. No global prototype mixin or compatibility flags are needed. ## Emptying a Region You can remove a view from a region (effectively "unshowing" it) with `region.empty()` on a region: ```javascript const myView = new MyView(); myView.showChildView('main', new OtherView()); const mainRegion = myView.getRegion('main'); mainRegion.empty(); ``` This will destroy the view, clean up any event handlers and remove it from the DOM. When a region is emptied [empty events are triggered](/docs/class-events.md#empty-and-beforeempty-events). Calling `empty()` after Region destruction completes returns the Region without resolving its element, changing the DOM, or emitting empty lifecycle events. **NOTE** If the region does _not_ currently contain a View it will detach any HTML inside the region when emptying. If the region _does_ contain a View, any HTML that doesn't belong to the View will remain. ### Preserving Existing Views If you replace the current view with a new view by calling `show`, it will automatically destroy the previous view. You can prevent this behavior by [detaching the view](#detaching-existing-views) before showing another one. ### Detaching Existing Views If you want to detach an existing view from a region, use `detachView`. ```javascript const myView = new MyView(); const myOtherView = new MyView(); const childView = new MyChildView(); // render and display the view myView.showChildView('main', childView); // ... somewhere down the line myOtherView.showChildView('main', myView.getRegion('main').detachView()); ``` **Note** Detaching transfers responsibility for the live View to the caller. Show it again in the same emptied Region or another Region when needed, or call `destroy()` when finished with it. ## `reset` A Region Resetting a live Region destroys its current View and restores its original `el` reference. An original selector is queried again by the next operation that needs it; an original DOM element is reused without a selector query. ```javascript const myView = new MyView(); myView.showChildView('main', new OtherView()); const myRegion = myView.getRegion('main'); myRegion.reset(); ``` This can be useful in unit testing your views. Calling `reset()` after Region destruction completes returns the Region without changing its element reference or cache. ## `destroy` A Region A region can be destroyed which will `reset` the region, destroy its current View, remove it from any parent View's Region lookups, and stop any internal Region listeners. Reentrant Region destruction from `before:destroy` or `destroy`, repeated calls, and later destruction of the parent View do not repeat the child or Region teardown. A throwing lifecycle hook stops destruction. Later `destroy()` calls do not retry hooks or resume partial teardown. Discard the Region after a cleanup error; its remaining state is not a reusable lifecycle state. `isDestroyed()` becomes `true` after `reset()` finishes, before the `destroy` event. It remains `false` in `before:destroy`, `before:empty`, and `empty` handlers called during teardown. `destroy()` calls the overridable `reset()` method, which calls `empty()`. Overrides can use this ordinary synchronous chain while cleanup is in progress. An override that does not delegate to the base method owns the corresponding cleanup; for example, a custom `reset()` can call `this.empty()` and reset its own element reference. Nested `empty()` or `reset()` calls from lifecycle handlers are ordinary calls, so handlers must avoid recursive loops. After destruction completes, `empty()` and `reset()` return the Region without changing its element or DOM. `show()` and `detachView()` already stop accepting Views or transferring ownership as soon as destruction begins. ```javascript import { View } from 'marionette'; const MyView = View.extend({ regions: { mainRegion: '#main' } }); const myView = new MyView(); myView.render(); const myRegion = myView.getRegion('mainRegion'); myRegion.show(new ChildView()); myRegion.destroy(); myRegion.isDestroyed(); // true myRegion.hasView(); // false myView.hasRegion('mainRegion'); // false ``` ## Check If View Is Being Swapped By Another The `isSwappingView` method returns if a view is being swapped by another one. It's useful inside region lifecycle events / methods. The example will show an message when the region is empty: ```javascript import { Region } from 'marionette'; const EmptyMsgRegion = Region.extend({ onEmpty() { if (!this.isSwappingView()) { this.el.append('Empty Region'); } } }); ``` ## Set How View's `el` Is Attached and Detached Override the region's `attachHtml` method to change how the view is attached to the DOM (when not using `replaceElement: true`). This method receives one parameter - the view to show. The default implementation of `attachHtml` is essentially: ```javascript import { Region } from 'marionette'; Region.prototype.attachHtml = function(view){ this.el.appendChild(view.el); } ``` Similar to `attachHtml`, override `detachHtml` to determine how the region detaches the contents from its `el`. This method receives no parameters. For most cases you will want to use the [DOM API](/docs/dom-api.md) to determine how a region html is attached, but in some cases you may want to override a single Region class for situations like animation where you want to control both attaching and [view removal](#configure-how-to-remove-view). This example will make a view slide down from the top of the screen instead of just appearing in place: ```javascript import $ from 'jquery'; import { Region, View } from 'marionette'; const ModalRegion = Region.extend({ attachHtml(view){ // Some effect to show the view: const $el = $(this.el); $el.empty().append(view.el); $el.hide().slideDown('fast'); } }); const MyView = View.extend({ regions: { mainRegion: '#main-region', modalRegion: { regionClass: ModalRegion, el: '#modal-region' } } }); ``` ## Configure How To Remove View Override the region's `removeView` method to change how and when the view is destroyed / removed from the DOM. This method receives one parameter - the view to remove. The default implementation of `removeView` is: ```javascript import { Region } from 'marionette'; Region.prototype.removeView = function(view){ this.destroyView(view); } ``` `destroyView(view)` destroys a Marionette View and returns it. It forwards the Region owner's lifecycle-monitoring policy; it does not adapt a Backbone View or fall back to `remove()`. Keep this helper when overriding `removeView`. Region operations are synchronous. A `removeView` override must complete cleanup before returning if callers should observe the normal empty/destroy contract. Returning a Promise does not delay Region lifecycle completion. For an exit animation, finish the animation in the application before calling `empty()` or showing the replacement, and let the Region perform its normal synchronous teardown. The application owns cancellation when navigation or destruction interrupts that animation. [Canonical source](/docs/markdown/docs/marionette.region.md) · [Source identity](/docs/manifest.json) --- Document: docs/marionette.collectionview.md Canonical URL: https://marionettejs.com/docs/collection-view/ Markdown URL: https://marionettejs.com/docs/collection-view.md Reading SHA-256: cf11a246ff891a207873733884de682c188895c5d1ca138168760c61d4ea4cd1 # Marionette.CollectionView A `CollectionView` manages repeated parts of a screen: rows, cards, or any ordered set of child views within a root element, `el`. It creates children from a `collection`, or lets you add and remove child views yourself. Plain arrays work with the default [Data API](/docs/data-api.md). Use an adapter when your collection needs to notify the view about changes; mutating a plain array does not send those notifications. `CollectionView` includes: - [The DOM API](/docs/dom-api.md) - [Class Events](/docs/class-events.md#collectionview-events) - [DOM Interactions](/docs/dom-interactions.md) - [Child Event Bubbling](/docs/events.md#event-bubbling) - [Entity Events](/docs/entity-events.md) - [View Rendering](/docs/rendering.md) - [Prerendered Content](/docs/prerendered-dom.md) - [View Lifecycle](/docs/lifecycle.md) A `CollectionView` can have [`Behavior`s](/docs/behavior.md). ## Documentation Index * [Instantiating a CollectionView](#instantiating-a-collectionview) * [Rendering a CollectionView](#rendering-a-collectionview) * [Rendering a Template](#rendering-a-template) * [Defining the `childViewContainer`](#defining-the-childviewcontainer) * [Re-rendering the CollectionView](#re-rendering-the-collectionview) * [View Lifecycle and Events](#view-lifecycle-and-events) * [Entity Events](#entity-events) * [DOM Interactions](#dom-interactions) * [Behaviors](#behaviors) * [Managing Children](#managing-children) * [Attaching `children` within the `el`](#attaching-children-within-the-el) * [Destroying All `children`](#destroying-all-children) * [CollectionView's `childView`](#collectionviews-childview) * [Building the `children`](#building-the-children) * [Passing Data to the `childView`](#passing-data-to-the-childview) * [CollectionView's `emptyView`](#collectionviews-emptyview) * [CollectionView's `getEmptyRegion`](#collectionviews-getemptyregion) * [Passing Data to the `emptyView`](#passing-data-to-the-emptyview) * [Defining When an `emptyView` shows](#defining-when-an-emptyview-shows) * [Accessing a Child View](#accessing-a-child-view) * [CollectionView `children` Iterators And Collection Functions](#collectionview-children-iterators-and-collection-functions) * [Listening to Events on the `children`](#listening-to-events-on-the-children) * [Self Managed `children`](#self-managed-children) * [Adding a Child View](#adding-a-child-view) * [Removing a Child View](#removing-a-child-view) * [Detaching a Child View](#detaching-a-child-view) * [Swapping Child Views](#swapping-child-views) * [Sorting the `children`](#sorting-the-children) * [Defining the `viewComparator`](#defining-the-viewcomparator) * [Maintaining the `collection`'s sort](#maintaining-the-collections-sort) * [Filtering the `children`](#filtering-the-children) * [Defining the `viewFilter`](#defining-the-viewfilter) ## Instantiating a CollectionView When instantiating a `CollectionView` there are several properties, if passed, that will be attached directly to the instance: `attributes`, `behaviors`, `childView`, `childViewContainer`, `childViewEventPrefix`, `childViewEvents`, `childViewOptions`, `childViewTriggers`, `className`, `collection`, `collectionEvents`, `el`, `emptyView`, `emptyViewOptions`, `events`, `id`, `model`, `modelEvents`, `sortWithCollection`, `stateEvents`, `tagName`, `template`, `templateContext`, `triggers`, `ui`, `viewComparator`, `viewFilter` ```javascript import { CollectionView } from 'marionette'; const myCollectionView = new CollectionView(); ``` `CollectionView` composes the same visual, event, and State contracts as `View`, but does not inherit View's named-Region methods. Use `getEmptyRegion()` for its empty View; put a CollectionView inside a parent View when a layout needs additional named Regions. A supplied `state` follows the [State ownership contract](/docs/state.md#borrowed-and-owned-sources). ## Rendering a CollectionView The `render` method of the `CollectionView` is primarily responsible for rendering the entire collection. It loops through each of the children in the collection and renders them individually as a `childView`. ```javascript import { CollectionView } from 'marionette'; const MyCollectionView = CollectionView.extend({}); // all of the children views will now be rendered. new MyCollectionView().render(); ``` ### Rendering a Template In addition to rendering children, the `CollectionView` may have a `template`. The child views can be rendered within a DOM element of this template. The `CollectionView` will serialize either the `model` or `collection` along with context for the `template` to render. For more detail on how to render templates, see [View Template Rendering](/docs/rendering.md). ### Defining the `childViewContainer` By default the `CollectionView` will render the children into the `el` of the `CollectionView`. If you are rendering a template you will want to set the `childViewContainer` to be a selector for an element within the template for child view attachment. ```javascript import { CollectionView } from 'marionette'; const MyCollectionView = CollectionView.extend({ childViewContainer: '.js-widgets', template: () => '

Widgets

' }); ``` **Errors** An error will throw if the childViewContainer can not be found. ### Re-rendering the CollectionView If you need to re-render the entire collection or the template, you can call the `collectionView.render` method. This method will destroy all of the child views that may have previously been added. ## View Lifecycle and Events Like `View`, a `CollectionView` exposes its lifecycle as the independent `isRendered()`, `isAttached()`, and `isDestroyed()` state values. Its managed children have their own View lifecycle state. Existing contents in the `CollectionView` element do not make the `CollectionView` rendered; rendering means its child set has been built and inserted into its element. The table describes the default rendered and monitored path. Passing `{ preventRender: true }` to `addChildView` still renders the parent when needed, but manages the supplied child without rendering it; detaching that child returns it in its current lifecycle state. Setting `monitorViewEvents: false` on the `CollectionView` intentionally disables child attachment events and automatic child `isAttached()` updates. Disabling monitoring does not make child destruction clear surrounding template content. Bulk removal is used only when the child container contains those Views' root elements and optional formatting whitespace. | Operation | CollectionView state | Managed child state | | --- | --- | --- | | Construct | Starts not rendered and not destroyed. It is attached only when its element is already in the document. | No children have been built. | | `render()` | Enters rendered and preserves its attached state. Repeated render stays rendered. | Builds and renders the current children. Repeated render destroys the previous children before building replacements. | | A rendered collection resets | Remains rendered and preserves its attached state. | Destroys the previous children and builds replacements for the reset collection. | | `addChildView(view)` | Renders first when needed, then remains rendered. | Renders and manages the added View. | | `detachChildView(view)` | State is unchanged. | Removes and returns the live View in a detached state. The caller becomes responsible for it. | | `removeChildView(view)` or external child destruction | State is unchanged. | Removes the child from the managed set. `removeChildView` destroys it; an externally destroyed child is removed once. | | The owning Region detaches and re-shows the CollectionView | Remains rendered while attached changes to `false`, then back to `true`. | Live children follow the parent's detached and attached state. | | `destroy()` | Detaches, becomes not rendered, and enters destroyed. Repeated destroy returns the CollectionView without repeating lifecycle events. | Detaches and destroys every still-managed child after the parent element is removed. | | `render()` after destruction | Returns the same CollectionView and remains not rendered and destroyed. Repeated calls are no-ops. | Does not recreate or render children. | | `addChildView(view)` once destruction begins | Returns the supplied View without inspecting it, the index, or options or changing events, ownership, DOM, or lifecycle state. Calls during `before:destroy` and repeated calls after destruction are the same no-op. | The supplied View remains unchanged and can be added to a live owner. | Collection `sort`, `reset`, and `update` events raised reentrantly during destruction do not rebuild, add, remove, sort, render, or destroy additional child Views. A View returned by `detachChildView()` is no longer managed by the `CollectionView`; another owner may show it, or the caller must destroy it. Other operations on an already destroyed `CollectionView` remain outside this lifecycle contract until their invalid-transition behavior is made consistent. Read More: - [View Lifecycle](/docs/lifecycle.md) - [View DOM Change Events](/docs/class-events.md#dom-change-events) - [View Destroy Events](/docs/class-events.md#destroy-events) ## Entity Events A `CollectionView` subscribes to its `model` and `collection` through the configured [DataApi](/docs/data-api.md). Event names and callback arguments belong to that data provider. Plain objects and arrays do not emit changes; declaring entity event maps for unobservable values throws `MN0037`. Read More: - [Entity Events](/docs/entity-events.md) ## DOM Interactions `CollectionView` uses the same native [`events`, `triggers`, and `ui` contracts](/docs/dom-interactions.md) as `View`. Keep parent selectors and handlers specific to DOM that the `CollectionView` itself owns. Delegation is rooted at the parent `el`, so a broad selector can also match child-owned descendants; do not rebind the parent's `ui` to reach into child View DOM. After application code places parent-owned DOM inside a template-less `CollectionView`, call `bindUIElements()` before reading it with `getUI()`. Use that method only to bind the CollectionView's own DOM, not child View DOM. Calling `getUI()` without a declared `ui` map or while UI elements are unbound throws [`MN0023`](/errors/MN0023.md). When parent code needs a child, [retrieve the child View through the public `children` lookup APIs](#accessing-a-child-view) and call an intentional public method on that View. For communication initiated by a child, use [`childViewEvents` or `childViewTriggers`](/docs/events.md#child-view-events), or an explicit public [`listenTo`](/docs/events.md#listening-to-events) subscription, instead of querying or mutating the child's DOM from the parent. Read More: - [DOM Interactions](/docs/dom-interactions.md) - [Listening to Events on Children](#listening-to-events-on-the-children) ## Behaviors A `Behavior` provides a clean separation of concerns to your view logic, allowing you to share common user-facing operations between your views. Read More: - [Using `Behavior`s](/docs/behavior.md#using-behaviors) ## Managing Children Children are automatically managed once the `CollectionView` is [rendered](#rendering-a-collectionview). For each model within the `collection` the `CollectionView` will build and store a `childView` within its `children` object. This allows you to easily access the views within the collection view, iterate them, find them by a given indexer such as the view's model or id and more. During its first render, the `CollectionView` subscribes through `DataApi.observeCollection()` to normalized update, reset, and reorder notifications. The configured provider owns the source event vocabulary; [Backbone](/docs/backbone.md) is one supported observable integration. When the `collection` for the view is `reset`, the view will destroy all children and re-render the entire collection. When the adapter reports a model addition, the `CollectionView` constructs its child and renders it if it passes the presentation filter. When a model is removed from the `collection` (or destroyed / deleted), the `CollectionView` will destroy and remove that model's child view. Collection updates, `sort()`, and `filter()` use the same child-rendering path. Surviving visible children keep their elements mounted, including when a `viewFilter` or custom `viewComparator` is active. New or newly visible children are attached through `attachHtml`; existing elements move only when their order needs to change. Removal alone does not move or rerender surviving children. See [DOM movement](/docs/dom-api.md#moveelel-parent-before) for focus and text-selection preservation and the browser fallback behavior. The `before:render:children` and `render:children` events receive all visible children. This describes the render pass, not a list of children whose templates were rerendered. Already-rendered children reuse their contents unless the data adapter reports them as updated. Overriding `sort()` or `filter()` replaces that part of the flow. Call the parent method to retain its behavior; CollectionView does not force a render after an override that deliberately skips it. When the `collection` for the view is sorted, the view by default reconciles its child views to the collection's source order unless the `sortWithCollection` attribute on the `CollectionView` is set to `false`. Setting `viewComparator: false` disables a separate presentation sort; it does not disable keyed source-order reconciliation. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const collection = new Backbone.Collection(); const MyChildView = View.extend({ template: false }); const MyCollectionView = CollectionView.extend({ childView: MyChildView, collection, }); const myCollectionView = new MyCollectionView(); // Collection view will not re-render as it has not been rendered collection.reset([{foo: 'foo'}]); myCollectionView.render(); // Collection view will effectively re-render displaying the new model collection.reset([{foo: 'bar'}]); ``` When the children are rendered the [`render:children` and `before:render:children` events](/docs/class-events.md#renderchildren-and-beforerenderchildren-events) will trigger. When a childview is added to the children [`add:child` and `before:add:child` events](/docs/class-events.md#addchild-and-beforeaddchild-events) will trigger When a childview is removed from the children [`remove:child` and `before:remove:child` events](/docs/class-events.md#removechild-and-beforeremovechild-events) will trigger. ### Attaching `children` within the `el` The `CollectionView` places new or newly visible child root elements into a `DocumentFragment`, then calls `attachHtml(fragment, container)` to insert that batch. Already mounted children remain in place or move only as needed to match the presentation order; they are not all removed and appended on each pass. You can override this by specifying an `attachHtml` method in your view definition. This method takes two parameters and has no return value. ```javascript import { CollectionView } from 'marionette'; CollectionView.extend({ // The default implementation: attachHtml(els, container) { // Unless childViewContainer is set, container === this.el this.Dom.appendContents(container, els); } }); ``` The first parameter is the DOM fragment containing child root elements, and the second parameter is the native DOM container for the children which by default equates to the view's `el` unless a [`childViewContainer`](#defining-the-childviewcontainer) is set. ### Destroying All `children` `CollectionView` implements a `destroy` method which automatically destroys its children and cleans up listeners. When a nonempty owned child set is destroyed, the [`destroy:children` and `before:destroy:children` events](/docs/class-events.md#destroychildren-and-beforedestroychildren-events) will trigger. Read More: - [View Destroy Events](/docs/class-events.md#destroy-events) ## CollectionView's `childView` When using a `collection` to manage the children of `CollectionView`, specify a Marionette `View` or `CollectionView` class as `childView`, rather than an instance. A plain Backbone View is not a supported child; [wrap it in a Marionette View](/docs/region.md#wrapping-a-non-marionette-view) when integrating a legacy component. ```javascript import { View, CollectionView } from 'marionette'; const MyChildView = View.extend({}); const MyCollectionView = CollectionView.extend({ childView: MyChildView }); ``` **Errors** When Marionette needs to construct a collection-backed child and `childView` is missing, it throws `MN0011`. An empty CollectionView or a CollectionView with only manually added children does not require `childView`. You can also define `childView` as a function. In this form, the value returned by this method is the `ChildView` class that will be instantiated when a `Model` needs to be initially rendered. This method also gives you the ability to customize per `Model` `ChildViews`. ```javascript import _ from 'underscore'; import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const FooView = View.extend({ template: _.template('foo') }); const BarView = View.extend({ template: _.template('bar') }); const MyCollectionView = CollectionView.extend({ collection: new Backbone.Collection(), childView(model) { // Choose which view class to render, // depending on the properties of the model if (model.get('isFoo')) { return FooView; } else { return BarView; } } }); const collectionView = new MyCollectionView().render(); const foo = new Backbone.Model({ isFoo: true }); const bar = new Backbone.Model({ isFoo: false }); // Renders a FooView collectionView.collection.add(foo); // Renders a BarView collectionView.collection.add(bar); ``` A resolver must return a Marionette View class. Core trusts that result; unsupported returns can fail later during construction or child setup. ### Building the `children` The `buildChildView` method is responsible for taking the ChildView class and instantiating it with the appropriate data. This method takes three parameters and returns a view instance to be used as the child view. ```javascript buildChildView(child, ChildViewClass, childViewOptions){ // build the final list of options for the childView class const options = { model: child, ...childViewOptions }; // create the child view instance const view = new ChildViewClass(options); // return it return view; }, ``` Override this method when you need a more complicated build, but use [`childView`](#collectionviews-childview) if you need to determine _which_ View class to instantiate. ```javascript import _ from 'underscore'; import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi } from 'marionette'; import MyListView from './my-list-view'; import MyView from './my-view'; setDataApi(BackboneApi); const MyCollectionView = CollectionView.extend({ childView(child) { if (child.get('type') === 'list') { return MyListView; } return MyView; }, buildChildView(child, ChildViewClass, childViewOptions) { let options; if (child.get('type') === 'list') { const childList = new Backbone.Collection(child.get('list')); options = _.extend({collection: childList}, childViewOptions); } else { options = _.extend({model: child}, childViewOptions); } // create the child view instance const view = new ChildViewClass(options); // return it return view; } }); ``` ### Passing Data to the `childView` There may be scenarios where you need to pass data from your parent collection view in to each of the childView instances. To do this, provide a `childViewOptions` definition on your collection view as an object literal. This will be passed to the constructor of your childView as part of the `options`. ```javascript import { View, CollectionView } from 'marionette'; const ChildView = View.extend({ initialize(options) { console.log(options.foo); // => "bar" } }); const MyCollectionView = CollectionView.extend({ childView: ChildView, childViewOptions: { foo: 'bar' } }); ``` You can also specify the `childViewOptions` as a function, if you need to calculate the values to return at runtime. The model will be passed into the function should you need access to it when calculating `childViewOptions`. The function may return an object, `null`, or `undefined`. The attributes of a returned object will be copied to the `childView` instance's options. Whether provided directly or returned by a function, the object's own enumerable properties, including symbols, are copied by object spread. `null` or `undefined` adds no extra options. A supplied `model` option overrides the source model; use that only when the child deliberately represents different data. ```javascript import { CollectionView } from 'marionette'; const MyCollectionView = CollectionView.extend({ childViewOptions(model) { // do some calculations based on the model return { foo: 'bar' }; } }); ``` ## CollectionView's `emptyView` When a collection has no children, and you need to render a view other than the list of childViews, you can specify an `emptyView` attribute on your collection view. The `emptyView`, like the [`childView`](#collectionviews-childview), can be passed as an option on instantiation. It must be a `View` class or a resolver that returns a `View` class. Marionette calls resolvers with the `CollectionView` as `this`; arrow and bound functions retain their normal JavaScript `this` semantics. If the resolved `emptyView` property is `undefined`, `null`, or `false`, no empty view is rendered. Because an `undefined` constructor option does not replace an inherited value, use `null` or `false` to disable an inherited definition. A resolver may return a `View` class or `undefined`, `null`, or `false` to disable the empty view. The public types describe these alternatives; Marionette trusts the result when the collection is empty. Errors thrown by a resolver propagate unchanged. When the empty collection is rendered or filtered again, a disabled result also removes any empty View already shown. ```javascript import _ from 'underscore'; import { View, CollectionView } from 'marionette'; const MyEmptyView = View.extend({ template: _.template('Nothing to display.') }); const MyCollectionView = CollectionView.extend({ // ... emptyView: MyEmptyView }); ``` ### CollectionView's `getEmptyRegion` When a `CollectionView` is instantiated it creates a region for showing the [`emptyView`](#collectionviews-emptyview). This region can be requested using the `getEmptyRegion` method. It uses the resolved `childViewContainer` when present, otherwise the CollectionView's `el`, and is shown with [`replaceElement: false`](/docs/region.md#additional-options). **Note** The `CollectionView` expects to be the only entity managing the region. Showing things in this region directly is not advised. ```javascript const isEmptyShowing = myCollectionView.getEmptyRegion().hasView(); ``` This region can be useful for handling the [EmptyView Region Events](/docs/class-events.md#collectionview-emptyview-region-events). ### Passing Data to the `emptyView` Similar to [`childView`](#collectionviews-childview) and [`childViewOptions`](#passing-data-to-the-childview), there is an `emptyViewOptions` property that will be passed to the `emptyView` constructor. It can be provided as an object literal or as a function. If `emptyViewOptions` aren't provided, the `CollectionView` falls back to `childViewOptions`. A callable definition receives no model argument and runs with the CollectionView as `this`; it must support that empty-view call. ```javascript import { View, CollectionView } from 'marionette'; const EmptyView = View.extend({ initialize(options){ console.log(options.foo); // => "bar" } }); const MyCollectionView = CollectionView.extend({ emptyView: EmptyView, emptyViewOptions: { foo: 'bar' } }); ``` ### Defining When an `emptyView` shows If you want to control when the empty view is rendered, you can override `isEmpty`: ```javascript import { CollectionView } from 'marionette'; const MyCollectionView = CollectionView.extend({ isEmpty() { // some logic to calculate if the view should be rendered as empty return this.collection.length < 2; } }); ``` The default implementation of `isEmpty` returns `!this.children.length`. Use `getEmptyRegion().hasView()` to determine whether an empty View is actually shown. `isEmpty()` alone does not establish that an `emptyView` was configured: ```javascript import { CollectionView } from 'marionette'; const MyCollectionView = CollectionView.extend({ // ... onRenderChildren() { if (this.getEmptyRegion().hasView()) { console.log('Empty View Shown'); } } }); ``` ## Accessing a Child View You can retrieve a view by a number of methods. If the findBy* method cannot find the view, it will return `undefined`. **Note** `children` is the current presentation container. It can include unrendered children added with `preventRender` until the next render/filter pass; filtered-out children remain owned but are absent from this container. ### CollectionView `children`'s: `findByCid` Find a view by its cid. ```javascript const bView = myCollectionView.children.findByCid(buttonView.cid); ``` ### CollectionView `children`'s: `findByModel` Find a view by `DataApi.key(model)`. With the default DataApi this is the model object identity. An adapter may use a stable key so that a new model object representing the same item resolves the currently indexed child. This lookup does not promise child retention when a collection observation replaces the model object; see [collection observations](/docs/data-api.md#collection-observations). ```javascript const bView = myCollectionView.children.findByModel(buttonView.model); ``` ### CollectionView `children`'s: `findByKey` `children.findByKey(key)` returns the View indexed by the exact key produced by its DataApi, or `undefined` when absent. Do not assume this key is the model's `id`: native Marionette and Backbone models use their provider's identity contract, while snapshot adapters can use an application-selected key. `children.hasView(view)` checks that the exact View instance is present under its `cid`; `children.contains(view)` checks instance membership as well. These lookups refer to the public presentation container. A filtered-out child can remain owned by the CollectionView without appearing in `children`. Keep an explicit reference when an application needs to detach such a child; do not reach into private containers. ### CollectionView `children`'s: `findByIndex` Find by numeric index (unstable) ```javascript const bView = myCollectionView.children.findByIndex(0); ``` ### CollectionView `children`'s: `findIndexByView` Find the index of the exact View inside `children`, or `-1` when absent. ```javascript const index = myCollectionView.children.findIndexByView(bView); ``` ### CollectionView `children` Iterators And Collection Functions The container is iterable: `for (const child of list.children)` visits the current presentation order. Use `children.toArray()` when you need a separate array before changing membership. The container owns the following iteration and collection functions: * `each` * `map` * `reduce` * `find` * `filter` * `reject` * `every` * `some` * `contains` * `invoke` * `toArray` * `first` * `initial` * `rest` * `last` * `without` * `isEmpty` * `pluck` * `partition` These methods can be called directly on the container, to iterate and process the views held by the container. `each`, `map`, `reduce`, `find`, `filter`, `reject`, `every`, `some`, and `partition` require callback functions. The public types enforce that contract; unsupported JavaScript callback shapes have no guaranteed Marionette diagnostic. String, object, and null iteratee shorthand is not supported. Structurally adding, removing, or reordering children while a callback runs is unsupported, and these methods do not promise call-start snapshot semantics. Mutating ordinary properties on a child View remains valid. `each(callback, context)` visits every child View in order, calls `callback` as `(view, index)`, binds `this` to `context` when provided, and returns the `children` container. An empty container returns itself without calling the callback. `map(callback, context)` calls `(view, index)` for every child View and returns a new ordered array of callback results. An empty container returns a new `[]`. Use `map(view => view.id)` or `pluck('id')` instead of property-name shorthand. `reduce(callback, initialValue, context)` calls `(accumulator, view, index)` in container order and binds optional `context`. When `initialValue` is supplied, every child View is visited; an empty container returns that exact value without calling the callback. When it is omitted, the first child View becomes the accumulator and traversal starts at index `1`. An empty container without an initial value throws [`MN0024`](/errors/MN0024.md). `pluck(key)` reads `key` directly from each child View. For example, `children.pluck('model')` returns the child Views' model objects, and a child without a model contributes `undefined`. It does not read model attributes; use an explicit callback such as `children.map(view => view.model?.get('status'))` for those values. Array-form deep paths are not traversed; replace `children.pluck(['model', 'cid'])` with `children.map(view => view.model?.cid)`. An empty container returns `[]`. `contains(value)` checks for the exact child View instance. A child View's model or another object with the same properties is not considered contained. An empty container returns `false`. `find`, `filter`, `reject`, `every`, `some`, and `partition` call their predicate with `(view, index)` and set `this` to optional `context`. `find(predicate, context)` returns the first child View for which the predicate is truthy, preserving View identity, and stops iterating at that match. It returns `undefined` when no View matches or the container is empty. `filter(predicate, context)` and `reject(predicate, context)` visit every child View and return new ordered arrays containing the Views for which the predicate is truthy or falsey, respectively. Changing a returned array does not change the container. An empty container returns `[]` without calling the predicate. `every(predicate, context)` returns `false` and stops at the first falsey result; otherwise it returns `true`. `some(predicate, context)` returns `true` and stops at the first truthy result; otherwise it returns `false`. For an empty container, `every` returns `true` and `some` returns `false`, without calling the predicate. `partition(predicate, context)` visits every child View and returns `[matchingViews, rejectedViews]`. Both members are new arrays that preserve the container order and contain the exact child View instances. An empty container returns `[[], []]` without calling the predicate. `invoke(methodName, ...args)` requires a direct string method name, invokes that method with each child View as `this`, forwards `args`, and returns a new ordered array of results. TypeScript restricts the name to callable child methods and checks their arguments and result types. Function-form and deep-path method names are not supported. An empty container returns `[]`. `toArray()` returns a new array containing the current child Views in container order. Changing the returned array's membership or order does not change the container. An empty container returns `[]`. Without a count, `first()` and `last()` return the first or last child View. With a nonnegative integer count, they return a new ordered array containing up to that many Views from the corresponding end of the container. A count of `0` returns `[]`. For an empty container, the no-count forms return `undefined` and the count forms return `[]`. `initial(count = 1)` and `rest(count = 1)` return new ordered arrays after excluding `count` Views from the end or start of the container, respectively. The count is a nonnegative integer: `0` returns a new array of every child View, and a count greater than or equal to the container length returns `[]`. An empty container also returns `[]`. `first`, `initial`, `rest`, and `last` throw [`MN0024`](/errors/MN0024.md) when a supplied count is not a nonnegative integer. `without(...views)` returns a new ordered array excluding the exact child View instances supplied. Models and lookalike objects do not exclude their associated Views. With no arguments it returns a new array of every child View. Changing the returned array's membership or order does not change the container. An empty container returns `[]`. `children.isEmpty()` reports whether the child container currently has zero Views. It is distinct from the overridable `CollectionView#isEmpty()` method, which controls whether a CollectionView renders its `emptyView`. The child container is iterable. `for...of`, spread, destructuring, and `Array.from(children)` yield the exact child View instances in container order. The iterator is defined once on the prototype rather than allocated as an own property on every container. The former undocumented Underscore aliases `forEach`, `detect`, `select`, `all`, `any`, and `include` are not part of the v5 container. Use `each`, `find`, `filter`, `every`, `some`, and `contains`, respectively. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi } from 'marionette'; setDataApi(BackboneApi); const collectionView = new CollectionView({ collection: new Backbone.Collection() }); collectionView.render(); // iterate over all of the views and process them collectionView.children.each(function(childView) { // process the `childView` here }); ``` ## Listening to Events on the `children` The `CollectionView` can take action depending on what events are triggered in its `children`. Read More: - [Child Event Bubbling](/docs/events.md#event-bubbling) ## Self-Managed `children` In addition to children added by Marionette matching the model of a `collection`, the `children` of the `CollectionView` can be manually managed. ### Adding a Child View The `addChildView` method can be used to add a view that is independent of your collection source. This method takes three parameters, the child view instance, optionally the index for where it should be placed within the [CollectionView's `children`](#managing-children), and an options hash. It returns the added view. ```javascript import { CollectionView, View } from 'marionette'; const ChildView = View.extend({ tagName: 'li', template() { return 'Model'; } }); export function runChildOwnershipLifecycle() { const collectionView = new CollectionView({ tagName: 'ul' }); const reusableChild = new ChildView(); const remainingChild = new ChildView(); collectionView.render(); collectionView.addChildView(reusableChild); const detachedChild = collectionView.detachChildView(reusableChild); collectionView.addChildView(detachedChild); collectionView.removeChildView(detachedChild); collectionView.addChildView(remainingChild); collectionView.destroy(); } ``` `detachChildView()` returns the same live View and transfers responsibility to the caller. That View may be added again without rendering it a second time. `removeChildView()` destroys the removed View, while destroying the `CollectionView` destroys every child that it still manages. An omitted or `null` index appends the child before sorting and filtering. The options-only form follows the same rule; use a numeric `index` to choose an insertion position. A numeric index bypasses sorting and filtering for that addition only. A later `sort()` or `filter()` processes the child normally. The numeric `index` in an options object takes precedence over the separate positional argument. **Errors** Adding a View that is still managed by a Region or `CollectionView` throws [`MN0003`](/errors/MN0003.md). Detach the View from its current owner before transferring it. Filtering a child out or adding it with `preventRender` still leaves it managed by that CollectionView. Use `detachChildView()` to transfer it to another owner. #### `preventRender` option If you wish to add a child view to the children without the collectionview rendering the children use the `preventRender` option. ```javascript import { CollectionView } from 'marionette'; import ButtonView from './button-view'; const myCollectionView = new CollectionView(); const insertIndex = 0; // Add to the top myCollectionView.addChildView(new ButtonView(), { preventRender: true, index: insertIndex }); myCollectionView.addChildView(new ButtonView(), insertIndex, { preventRender: true }); myCollectionView.addChildView(new ButtonView()); // renders all three children ``` ### Removing a Child View The `removeChildView` method is useful if you need to remove and destroy a view from the `CollectionView` without affecting the view's collection. In most cases it is better to use the data to determine what the `CollectionView` should display. This method accepts the child view instance to remove as its parameter. It returns the removed view. Later updates to the retained model do not recreate its removed View. Rendering the CollectionView again or resetting its collection rebuilds its children from the current collection. ```javascript import { CollectionView } from 'marionette'; // Fragment for a collection using the Backbone DataApi. const MyCollectionView = CollectionView.extend({ childViewEvents: { 'foo:event': 'onChildViewFooEvent' }, onChildViewFooEvent(childView, model) { // NOTE: we must wait for the server to confirm // the destroy PRIOR to removing it from the collection model.destroy({wait: true}); // but go ahead and remove it visually this.removeChildView(childView); } }); ``` ### Detaching a Child View The `detachChildView` method is the same as [`removeChildView`](#removing-a-child-view) with the exception that the removed view is not destroyed. ### Swapping Child Views Swap the location of two views in the `CollectionView` `children` and in the `el`. This can be useful when sorting is arbitrary or is not performant. **Errors** If either of the two views aren't part of the `CollectionView` an error will be thrown. If only one of the two children is in the presentation `children` container, [filter](#filtering-the-children) is called after swapping their owned order. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi } from 'marionette'; import MyChildView from './my-child-view'; setDataApi(BackboneApi); const collection = new Backbone.Collection([ { name: 'first' }, { name: 'middle' }, { name: 'last' } ]); const myColView = new CollectionView({ collection: collection, childView: MyChildView }); myColView.render(); myColView.swapChildViews(myColView.children.first(), myColView.children.last()); myColView.children.first().model.get('name'); // "last" myColView.children.last().model.get('name'); // "first" ``` ## Sorting the `children` The `sort` method will loop through the `CollectionView` `children` prior to filtering and sort them with the [`viewComparator`](#defining-the-viewcomparator). By default, if a `viewComparator` is not set, the `CollectionView` will sort the views by the order of the models in the `collection`. If set to `false`, presentation sorting is disabled. Normalized collection observations still reconcile the keyed children to source order when `sortWithCollection` is enabled. This method is called internally when rendering. [`sort` and `before:sort` events](/docs/class-events.md#sort-and-beforesort-events) fire when owned children exist and a comparator is active. By default the `CollectionView` will maintain a sorted collection's order in the DOM. This behavior can be disabled by specifying `{sortWithCollection: false}` on initialize. Default source ordering uses each notification's captured snapshot. A nested notification waits for the current sort, filter, and render pass to finish. Calling `sort()` outside a collection notification reads the current source after `before:sort`. With the default comparator, manually added children whose models are absent from the source stay before the source children. Custom comparators still determine their own order and data reads. With `sortWithCollection` enabled, source order breaks ties and manually added children follow source children on ties. With it disabled, ties retain the existing child order. ### Defining the `viewComparator` `CollectionView` allows for a custom `viewComparator` option if you want your `CollectionView`'s children to be rendered with a different sort order than the underlying collection uses. ```javascript import { CollectionView, View } from 'marionette'; const RowView = View.extend({ template: ({ rank }) => String(rank) }); const myCollectionView = new CollectionView({ collection: [{ rank: 2 }, { rank: 1 }], childView: RowView, viewComparator: 'rank' }); ``` ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const RowView = View.extend({ template: ({ id }) => String(id) }); const myCollection = new Backbone.Collection([ { id: 1 }, { id: 4 }, { id: 3 }, { id: 2 } ]); myCollection.comparator = 'id'; const myDescendingView = new CollectionView({ childView: RowView, collection: myCollection, viewComparator: childView => -childView.model.id }); const mySourceOrderView = new CollectionView({ childView: RowView, collection: myCollection, viewComparator: false }); myDescendingView.render(); // 4 3 2 1 mySourceOrderView.render(); // 1 4 3 2 myCollection.sort(); // myDescendingView remains 4 3 2 1 // mySourceOrderView reconciles to source order: 1 2 3 4 ``` A `viewComparator` can be a one-argument criterion function, a two-argument comparison function, or a string naming a model attribute read through DataApi. Functions receive child Views, not models, and run with the CollectionView as `this`. These forms do not require Backbone. A string or single-argument comparator evaluates one criterion per child View and sorts stably. Equal, `NaN`, or otherwise incomparable criteria retain their existing order, while `undefined` criteria sort last. A string comparator therefore places a child without a model last. Two-argument comparators retain native `Array#sort` semantics. Sorting keeps the same `children` container in use. If evaluating or comparing a single-argument criterion throws, the error propagates without changing the child order. #### `getComparator` Override this method to determine which `viewComparator` to use. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import { CollectionView, setDataApi } from 'marionette'; setDataApi(BackboneApi); const MyCollectionView = CollectionView.extend({ sortAsc(view) { return view.model.get('order'); }, sortDesc(view) { return -view.model.get('order'); }, getComparator() { // The collectionView's model if (this.model.get('sorted') === 'ASC') { return this.sortAsc; } return this.sortDesc; } }); ``` #### `setComparator` The `setComparator` method updates `viewComparator` and calls `sort()` when the value changes. `{ preventRender: true }` defers that sort/filter/child-render pass. It returns the CollectionView and does not run the parent `before:render`/`render` lifecycle. Call it after initial rendering, or defer the pass until the initial `render()`. ```javascript import { CollectionView, View } from 'marionette'; const RowView = View.extend({ template: ({ orderBy }) => String(orderBy) }); const cv = new CollectionView({ collection: [{ orderBy: 2 }, { orderBy: 1 }], childView: RowView }); cv.render(); // Note: the setComparator is preventing the automatic re-render cv.setComparator('orderBy', { preventRender: true }); // Apply the order without rebuilding the children or parent template cv.sort(); ``` #### `removeComparator` This function is actually an alias of `setComparator(null, options)`. It is useful for removing the comparator. `removeComparator` also accepts `preventRender` as a option. ```javascript import { CollectionView, View } from 'marionette'; const RowView = View.extend({ template: ({ orderBy }) => String(orderBy) }); const cv = new CollectionView({ collection: [{ orderBy: 2 }, { orderBy: 1 }], childView: RowView }); cv.render(); cv.setComparator('orderBy'); //Remove the current comparator without rendering again. cv.removeComparator({ preventRender: true }); ``` ### Maintaining the `collection`'s sort By default the `CollectionView` will maintain a sorted collection's order in the DOM. This behavior can be disabled by specifying `{sortWithCollection: false}` on initialize or on the view definiton. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const RowView = View.extend({ template: ({ id }) => String(id) }); const myCollection = new Backbone.Collection([ { id: 1 }, { id: 4 }, { id: 3 }, { id: 2 } ]); myCollection.comparator = 'id'; const mySortedColView = new CollectionView({ childView: RowView, collection: myCollection }); const myUnsortedColView = new CollectionView({ childView: RowView, collection: myCollection, sortWithCollection: false }); mySortedColView.render(); // 1 4 3 2 myUnsortedColView.render(); // 1 4 3 2 myCollection.sort(); // mySortedColView auto-renders 1 2 3 4 // myUnsortedColView has no change ``` ## Filtering the `children` The `filter` method will loop through the `CollectionView`'s sorted `children` and test them against the [`viewFilter`](#defining-the-viewfilter). The views that pass the `viewFilter` are rendered if necessary and attached to the CollectionView and the views that are filtered out will be detached. After filtering the `children` will only contain the views to be attached. If owned children exist and an active `viewFilter` is applied, the [`filter` and `before:filter` events](/docs/class-events.md#filter-and-beforefilter-events) will trigger. The CollectionView refilters during normalized collection updates and sorting. An arbitrary child property change does not itself trigger filtering; call `filter()` when application-owned presentation criteria change. **Note** This is a presentation functionality used to easily filter in and out constructed children. All children of a `collection` will be instantiated once regardless of their filtered status. If you would prefer to manage child view instantiation, you should filter the `collection` itself. ### Defining the `viewFilter` `CollectionView` allows for a custom `viewFilter` option if you want to prevent some of the underlying `children` from being attached to the DOM. A `viewFilter` can be a function, predicate object, or string. Use `null` or `false` to disable it. Other shapes are unsupported; core does not guarantee a diagnostic for an invalid filter. #### `viewFilter` as a function The `viewFilter` function takes a view from the `children` and returns a truthy value if the child should be attached, and a falsey value if it should not. It runs with the `CollectionView` as `this` and receives the child View, index, and the live backing child array. A filter pass captures the array's initial length, visits every index densely, and does not visit entries appended during that pass. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const SomeChildView = View.extend({ template: ({ value }) => String(value) }); const SomeEmptyView = View.extend({ template: () => 'No matches' }); const cv = new CollectionView({ childView: SomeChildView, emptyView: SomeEmptyView, collection: new Backbone.Collection([ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 } ]), // Only show views with even values viewFilter(view, index, children) { return view.model.get('value') % 2 === 0; } }); // renders the views with values '2' and '4' cv.render(); ``` #### `viewFilter` as a predicate object The `viewFilter` predicate object will filter against the view's model attributes. Each filter pass snapshots the predicate's own enumerable string keys and values in standard JavaScript own-key order. Inherited, symbol, and non-enumerable keys are ignored. Every predicate key must exist in the model attributes and its value must compare strictly equal; nested objects therefore match by identity. Arrays are not predicate objects. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const SomeChildView = View.extend({ template: ({ value }) => String(value) }); const SomeEmptyView = View.extend({ template: () => 'No matches' }); const cv = new CollectionView({ childView: SomeChildView, emptyView: SomeEmptyView, collection: new Backbone.Collection([ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 } ]), // Only show views with value 2 viewFilter: { value: 2 } }); // renders the view with values '2' cv.render(); ``` #### `viewFilter` as a string The `viewFilter` string represents the view's model attribute and will filter truthy values. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const SomeChildView = View.extend({ template: ({ value }) => String(value) }); const SomeEmptyView = View.extend({ template: () => 'No matches' }); const cv = new CollectionView({ childView: SomeChildView, emptyView: SomeEmptyView, collection: new Backbone.Collection([ { value: 0 }, { value: 1 }, { value: 2 }, { value: null }, { value: 4 } ]), // Only show views 1,2, and 4 viewFilter: 'value' }); // renders the view with values '1', '2', and '4' cv.render(); ``` #### `getFilter` Override this function to programatically decide which `viewFilter` to use when `filter` is called. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import { CollectionView, setDataApi } from 'marionette'; setDataApi(BackboneApi); const MyCollectionView = CollectionView.extend({ summaryFilter(view) { return view.model.get('type') === 'summary'; }, getFilter() { if (this.collection.length > 100) { return this.summaryFilter; } return this.viewFilter; } }); ``` #### `setFilter` The `setFilter` method updates `viewFilter` and calls `filter()` when the value changes. `{ preventRender: true }` defers that filter/child-render pass. It returns the CollectionView without running the parent render lifecycle. Call it after initial rendering, or defer the pass until the initial `render()`. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const RowView = View.extend({ template: ({ value }) => String(value) }); const cv = new CollectionView({ collection: new Backbone.Collection([{ value: 1 }, { value: 2 }]), childView: RowView }); cv.render(); const newFilter = function(view, index, children) { return view.model.get('value') % 2 === 0; }; // Note: the setFilter is preventing the automatic re-render cv.setFilter(newFilter, { preventRender: true }); // Apply the new filter while retaining surviving child instances. cv.filter(); ``` #### `removeFilter` This function is actually an alias of `setFilter(null, options)`. It is useful for removing filters. `removeFilter` also accepts `preventRender` as a option. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { CollectionView, setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const RowView = View.extend({ template: ({ value }) => String(value) }); const cv = new CollectionView({ collection: new Backbone.Collection([{ value: 1 }, { value: 2 }]), childView: RowView }); cv.render(); cv.setFilter(function(view, index, children) { return view.model.get('value') % 2 === 0; }); // Remove the current filter without rendering again. cv.removeFilter({ preventRender: true }); ``` [Canonical source](/docs/markdown/docs/marionette.collectionview.md) · [Source identity](/docs/manifest.json) --- Document: docs/marionette.application.md Canonical URL: https://marionettejs.com/docs/application/ Markdown URL: https://marionettejs.com/docs/application.md Reading SHA-256: 11b56bbb20e7d69fd623a56103d865d4e28299d34e0cda6cc778e8d14ffea8a8 # Marionette.Application An `Application` gives a feature a place to start, stop, restart, and clean up. It coordinates asynchronous work and child Applications, with an optional Region for the feature's view tree. `Application` includes: - [Common Marionette Functionality](/docs/common.md) - [Class Events](/docs/class-events.md#application-events) - [Radio API](/docs/radio.md#marionette-integration) - [State API](/docs/state.md#borrowed-and-owned-sources) `Application` is an independent class. It does not inherit from `MnObject` and does not add an element or render method. The `Application` `cidPrefix` is `mna`. ## Documentation Index * [Instantiating An Application](#instantiating-an-application) * [Application Lifecycle](#application-lifecycle) * [Application Ownership](#application-ownership) * [Application and root View communication](#application-and-root-view-communication) * [Application State](#application-state) * [Application Region](#application-region) * [Application Region Methods](#application-region-methods) ## Instantiating an Application When instantiating an `Application` there are several properties, if passed, that will be attached directly to the instance: `channelName`, `radioEvents`, `radioRequests`, `region`, `regionClass`, `stateEvents` ```javascript import { Application } from 'marionette'; const myApplication = new Application(); ``` ### Initialization hooks `preinitialize(options)` runs after `options` and `cid` are assigned, before Marionette sets up the Region, Radio, and State. Use it to prepare instance configuration those steps depend on. `initialize(options)` runs after that setup, before State event subscriptions are connected. Owned State is still created lazily when `getState()` is first called. ```javascript const FeatureApplication = Application.extend({ preinitialize(options) { this.channelName = options.featureName; this.region = { el: options.element }; }, initialize() { // The configured Region and Radio channel are now available. } }); ``` Both hooks receive the original constructor arguments and run synchronously; returned Promises are not awaited. Use `onBeforeStart` for asynchronous startup readiness. Constructor errors propagate to the caller. Marionette does not undo partially completed initialization or automatically release resources from a constructor that throws. See the shared [synchronous failure boundary](/docs/lifecycle.md#synchronous-failures). Application's asynchronous lifecycle has its own cancellation and failure contract, described below. ## Application Lifecycle `start`, `stop`, `restart`, and `destroy` return a `Promise`. The Promise resolves `true` when the requested target state is reached, including an idempotent call when that state is already current. It resolves `false` when a later incompatible operation supersedes the request. `false` is cancellation, not failure. A current lifecycle hook failure rejects its operation Promise. Compatible repeated calls share the in-flight Promise. Before destruction begins, the latest incompatible operation wins: for example, `stop()` during startup resolves the earlier `start()` as `false`, completes the stop lifecycle, and prevents a stale `start` event. A `start()` that supersedes an in-flight stop waits for the already-running `onBeforeStop` readiness hook before beginning startup; it does not emit the invalidated `stop` completion. Once destruction begins it is terminal; `start()` and `restart()` resolve `false`, while `stop()` follows the active teardown until it has reached a stopped or destroyed state. Completion of an invalidated asynchronous hook cannot change the Application's running or destroyed state or emit the invalidated success event. `isRunning()` is `true` only after startup readiness completes and while the Application is running. It is `false` before the first start, during lifecycle transitions, after stop, and after destroy. ### Lifecycle operations | Current condition | Operation | Lifecycle | Result | | --- | --- | --- | --- | | Not running | `start(options)` | `before:start`, await readiness, `start` | `true` when running | | Running | `start(options)` | No-op | `true` | | Running or starting | `stop(options)` | Invalidates startup when needed, then `before:stop`, `stop` | `true` when stopped; the invalidated start resolves `false` | | Stopped | `stop(options)` | Empty a root View shown outside startup; otherwise no-op | `true` | | Any live, non-destroying state | `restart(options)` | Stop when needed, then start | `true` when running | | Running or starting | `destroy(options)` | Stop when needed, then `before:destroy`, `destroy` | `true` when destroyed | | Stopped | `destroy(options)` | `before:destroy`, `destroy` | `true` when destroyed | | Destroying | repeated `destroy()` | Shares the active destroy lifecycle | Same in-flight Promise | | Destroying | `start()` or `restart()` | Terminal no-op | `false` | | Destroying | `stop()` | Follows active teardown without interrupting it | `true` once stopped or destroyed; rejects if teardown fails before stopping | | Destroyed | `start()` or `restart()` | Terminal no-op | `false` | | Destroyed | `stop()` or `destroy()` | Terminal no-op | `true` | The `onBeforeStart`, `onBeforeStop`, and `onBeforeDestroy` methods may return a Promise. Their corresponding `before:*` events still fire synchronously, but event-listener return values are not readiness inputs. `onStart`, `onStop`, `onDestroy`, and their matching events are completion notifications and are not awaited. A `before:*` method must not await the same operation whose readiness it is defining. `restart` composes the stop and start lifecycles; it does not add a parallel restart hook path. Each readiness hook and `before:*` event receives the Application, the operation options, and a context object with an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal): `(application, options, { signal })`. When a later operation invalidates readiness, Marionette aborts its signal before starting replacement readiness. The signal makes cancellation cooperative; the invalidated operation still resolves `false` even when a handler ignores it. When a start, restart, or destroy operation adopts an in-flight stop phase, it also adopts that phase's original options and context, and does not abort its signal. If a replacement start has already canceled the remaining child stops, that stop phase is no longer adopted. A later `stop()`, `restart()`, or `destroy()` begins a fresh stop phase with its own options and context. The context belongs to the readiness phase rather than to one caller's Promise. Completion methods and events receive only `(application, options)`. Owned child Applications participate in the same operation. After the owner's `before:start` readiness, children start sequentially in registration order before the owner reaches running and emits `start`. After `before:stop` readiness, children stop in that order before the owner reaches stopped and emits `stop`. Restart and destroy compose those same phases. If a direct child operation supersedes an owner-requested child start or stop, the owner operation resolves `false`, retains its prior stable state, and does not emit its completion event. Children that already reached the requested state remain there. `isRunning()` describes that Application, not an aggregate of every descendant state; callers receiving `false` can inspect child state through the public hierarchy. Once owner destruction begins, descendant `start` and `restart` calls resolve `false` so they cannot interrupt terminal teardown. ### Starting an Application Once configured, await `start(options)` before dispatching work that requires a running Application. The optional argument is passed to the lifecycle methods and events. The application below loads a session before showing its root View. The supplied `loadSession({ signal })` function returns a Promise for an object with a `name` string. It can use `fetch`, a cache, or the project's existing data layer. ```javascript import { Application, View } from 'marionette'; const SessionView = View.extend({ template: () => '

', onRender() { this.el.querySelector('h1').textContent = this.model.name; } }); export function createSessionApplication({ el, loadSession }) { const SessionApplication = Application.extend({ async onBeforeStart(app, options, { signal }) { const session = await loadSession({ signal }); if (signal.aborted) return; this.session = session; }, onStart() { this.showView(new SessionView({ model: this.session })); } }); return new SessionApplication({ region: { el } }); } ``` Create and start it at the application entry point: Serve this application and its API over HTTPS in production; relative requests use the application origin. ```javascript const app = createSessionApplication({ el: document.querySelector('#root-element'), async loadSession({ signal }) { const response = await fetch('/api/bootstrap', { signal }); if (!response.ok) throw new Error(`Session request failed: ${response.status}`); return response.json(); } }); const started = await app.start(); if (started) { // Dispatch work that requires the running feature. } ``` Check the readiness signal after asynchronous work and before mutating application state. Marionette prevents a canceled operation from emitting its success event, but cannot undo a stale assignment inside application code. A current loader failure rejects `start()`; handle it at the application entry point. Route registration and browser-history startup belong to the router's owner, outside a feature's restartable `onStart` hook. See [router integration](/docs/routing.md) for per-navigation loading and cancellation. ## Application Ownership An Application may own named child Applications. Ownership is one-way: an Application locates and controls its children, while children receive required collaborators explicitly. Internal parent references exist only to enforce lifecycle and unlink children safely; upward lookup is not public API. `addChildApp(name, application)` registers an existing live, parentless Application instance under a non-empty string name and returns that instance. Registration does not construct or implicitly start the child. Use `hasChildApp(name)` before constructing a dynamic child when duplicate allocation matters. Registering the same instance again under its existing owner and name is an idempotent no-op. A conflicting owner, name, runtime, or cyclic ownership relationship throws [`MN0031`](/errors/MN0031.md). Calls to `addChildApp` after the owner's destruction begins return the supplied value without inspecting or adopting it. A child from the same runtime whose destruction has begun is also returned without registration. Live registrations require the owner and child to belong to the same Marionette runtime. ```javascript const root = new Application(); if (!root.hasChildApp('search')) { root.addChildApp('search', new SearchApplication()); } const search = root.getChildApp('search'); search.getName(); // 'search' root.getChildApps(); // { search } ``` `getChildApps()` returns a fresh snapshot. Changing the snapshot does not change ownership. Child lookup methods are reads; they do not start, render, or otherwise mutate an Application. Owner lifecycle options are forwarded to each child. A child failure rejects the owner operation and leaves the owner in its last committed stable state. Children that already reached the requested state remain there; retry visits the same registration order, where completed child operations are idempotent. An owner transition completes only after every child remains in the requested stable state. A direct opposing child operation cancels the owner transition, and superseding the owner from `before:start` or `before:stop` prevents the stale transition from changing any further children. `removeChildApp(name, options)` destroys the named child and resolves with it after destruction. An unknown name resolves with `undefined`. A child also removes itself from its parent's child hierarchy when destroyed directly. A running parent stops its children before `before:destroy`, then destroys owned children in registration order and finally emits the parent's `destroy` completion. A parent's `onBeforeDestroy` readiness hook can therefore inspect its stopped, live children. A stopped parent also stops any child that was started directly before entering destroy readiness. A concurrent direct child destroy joins terminal teardown and may remove that child before parent readiness. If child stop or destroy readiness fails, the parent returns to its last committed stable state and retains that child so destruction can be retried. The canonical child-Application pattern is explicit construction followed by ownership registration. Registration means lifecycle ownership; it is not a dormant service registry and it has no per-child lifecycle flags. Put a service that must outlive an Application under a longer-lived owner and pass it to the shorter-lived child as a dependency. ```javascript import { Application } from 'marionette'; export const lifecycle = []; const SearchApplication = Application.extend({ onBeforeStart(app, options) { lifecycle.push(`search:before:start:${ options.source }`); }, onStart(app, options) { lifecycle.push(`search:start:${ options.source }`); }, onBeforeStop(app, options) { lifecycle.push(`search:before:stop:${ options.source }`); }, onStop(app, options) { lifecycle.push(`search:stop:${ options.source }`); }, onDestroy() { lifecycle.push('search:destroy'); } }); const RootApplication = Application.extend({ onBeforeStart(app, options) { lifecycle.push(`root:before:start:${ options.source }`); }, onStart(app, options) { lifecycle.push(`root:start:${ options.source }`); }, onBeforeStop(app, options) { lifecycle.push(`root:before:stop:${ options.source }`); }, onStop(app, options) { lifecycle.push(`root:stop:${ options.source }`); }, onDestroy() { lifecycle.push('root:destroy'); } }); export const root = new RootApplication(); export const search = root.addChildApp('search', new SearchApplication()); export const started = await root.start({ source: 'owner' }); export const stopped = await root.stop({ source: 'owner' }); ``` ## Application and root View communication Keep the ownership direction visible. The Application constructs the root View, passes dependencies and initial values down through its options or public methods, and listens to semantic View events for messages back up. The View should not find its Application through DOM ancestry or private ownership fields. Use Radio only when the sender and receiver do not share this direct ownership boundary. ```javascript import { Application, View } from 'marionette'; export const refreshes = []; const DashboardView = View.extend({ initialize(options) { this.initialStatus = options.initialStatus; }, template() { return '

'; }, events: { 'click .refresh': 'requestRefresh' }, onRender() { this.showStatus(this.initialStatus); }, requestRefresh() { this.trigger('refresh:requested', this, { source: 'button' }); }, showStatus(status) { this.el.querySelector('.status').textContent = status; } }); const DashboardApplication = Application.extend({ region: '#dashboard', onStart() { const view = new DashboardView({ initialStatus: 'Idle' }); this.listenTo(view, 'refresh:requested', this.refreshDashboard); this.showView(view); }, refreshDashboard(view, request) { refreshes.push(request); view.showStatus('Updated'); } }); export const dashboard = new DashboardApplication(); await dashboard.start(); export const dashboardView = dashboard.getView(); ``` ## Application state An Application may compose one [state source](/docs/state.md). A supplied `state` is borrowed; a `createState(options)` result is owned. `getState()` returns the exact source, and `stateEvents` are installed through the selected StateApi after `initialize`. Application state persists across stop and restart. Destruction releases its subscriptions, then disposes its owned state source through StateApi. Stateless Applications allocate no source or subscription. Asynchronous startup work must use the readiness context's abort signal before committing values so invalidated startup cannot apply stale changes. ## Application Region An `Application` coordinates one root View through a single [region](/docs/region.md). The `region` property can be [defined in multiple ways](/docs/region.md#defining-regions). ```javascript import { Application } from 'marionette'; import RootView from './views/root'; const MyApp = Application.extend({ region: '#root-element', onStart() { this.showView(new RootView()); } }); const myApp = new MyApp(); await myApp.start(); ``` The `onStart` callback synchronously renders and shows `RootView`. `before:render` and `render` run for its template; `before:attach` and `attach` also run when the Region is attached to a document and lifecycle monitoring is enabled. `start()` itself remains asynchronous. `region` can also be passed as an option during instantiation. The Application owns a Region that it constructs from a selector, Region class, or definition object. Passing an existing Region instance instead borrows that host. Stopping the Application empties the Region's current View, including one shown directly through the Region. Destroying the Application also destroys a Region it constructed, but never destroys a borrowed Region. The Application's View is whatever its Region currently shows. Showing a View through either `app.showView(view)` or `app.getRegion().show(view)` updates what `app.getView()` returns. Emptying or detaching the Region leaves no current View without stopping the Application. Restart removes the current View before `onStart` may show a new View. If the Region has no View, stopping the Application leaves any unmanaged HTML alone. ### `regionClass` By default the [`Region`](/docs/region.md) is used to instantiate the `Application`'s region. An extended Region can be provided to the `Application` definition to override the default. ```javascript import { Application, Region } from 'marionette'; const MyRegion = Region.extend({ isSpecial: true }); const MyApp = Application.extend({ regionClass: MyRegion }); const myApp = new MyApp({ region: '#foo' }); myApp.getRegion().isSpecial; // true ``` `regionClass` can also be passed as an option during instantiation. ## Application Region Methods The Marionette Application provides helper methods for managing its attached region. ### `getRegion()` Return the current host [region object](/docs/region.md) for the Application, or `undefined` if none was configured. This synchronous query does not resolve its element or render a View. The host reference is released when the Application is destroyed. ### `showView(view, options)` Display a `View` instance in the Region attached to the Application. This runs the [`View lifecycle`](/docs/lifecycle.md). The Application itself is never passed to `Region#show` and does not become renderable. This method is synchronous and returns the supplied View, forwarding `options` to `Region#show`. Configure a Region before calling it. It does not call `start()` or wait for Application readiness. Once destruction begins it returns the supplied View without displaying or adopting it. A missing element allowed by `allowMissingEl` also leaves the View caller-owned; use `getView() === view` to check that it was shown. ### `getView()` Return the Region's `currentView`, including a View shown directly through the Region or before Application startup. Returns `undefined` when the Region has no current View or the Application has no Region. [Canonical source](/docs/markdown/docs/marionette.application.md) · [Source identity](/docs/manifest.json) --- Document: docs/marionette.behavior.md Canonical URL: https://marionettejs.com/docs/behavior/ Markdown URL: https://marionettejs.com/docs/behavior.md Reading SHA-256: 7bdf6ecba5120701c4500a6d104817365230b455c183b811bbc1aae34fce7457 # Marionette.Behavior A `Behavior` shares interaction logic across views. It uses its host view's DOM and can handle DOM, model, and collection events without giving each view another copy of the same handlers. `Behavior` includes: - [Common Marionette Functionality](/docs/common.md) - [Class Events](/docs/class-events.md#behavior-events) - [DOM Interactions](/docs/dom-interactions.md) - [Entity Events](/docs/entity-events.md) [Attach a Behavior class to a view](#using-behaviors) through its `behaviors` definition. The view constructs the Behavior and manages its lifetime. ## Documentation Index * [Instantiating a Behavior](#instantiating-a-behavior) * [Using Behaviors](#using-behaviors) * [Defining and Attaching Behaviors](#defining-and-attaching-behaviors) * [Behavior Options](#behavior-options) * [Nesting Behaviors](#nesting-behaviors) * [The Behavior's `view`](#the-behaviors-view) * [Host Communication and Event Proxies](#host-communication-and-event-proxies) * [Host and Behavior Events](#host-and-behavior-events) * [Proxy Handlers](#proxy-handlers) * [Initialize Order](#initialize-order) * [Using `ui`](#using-ui) * [Host DOM Boundary](#host-dom-boundary) * [Behavior Lifecycle](#behavior-lifecycle) * [Destroying a Behavior](#destroying-a-behavior) ## Instantiating a Behavior Unlike other [Marionette classes](/docs/classes.md), `Behavior`s are not meant to be instantiated except by a view. ## Using Behaviors The easiest way to see how to use the `Behavior` class is to take an example view and factor out common behavior to be shared across other views. ```javascript import { View } from 'marionette'; const MyView = View.extend({ template() { return ''; }, ui: { destroy: '.destroy-btn' }, events: { 'click @ui.destroy': 'warnBeforeDestroy' }, warnBeforeDestroy() { alert('This view will be removed.'); this.destroy(); }, onRender() { this.getUI('destroy')[0].title = 'What a nice mouse you have.'; } }); ``` Interaction points, such as tooltips and warning messages, are generic concepts. There is no need to recode them within your Views so they are prime candidates to be extracted into `Behavior` classes. ### Defining and Attaching Behaviors ```javascript import { Behavior, View } from 'marionette'; const DestroyWarn = Behavior.extend({ // You can set default options // They will be overridden if you pass in an option with the same key. options: { message: 'You are destroying!' }, ui: { destroy: '.destroy-btn' }, // Behaviors have events that are bound to the view's DOM. events: { 'click @ui.destroy': 'warnBeforeDestroy' }, warnBeforeDestroy() { const message = this.getOption('message'); window.alert(message); // Every Behavior has a hook into the // view that it is attached to. this.view.destroy(); } }); const ToolTip = Behavior.extend({ options: { text: 'Tooltip text' }, ui: { tooltip: '.tooltip' }, onRender() { this.getUI('tooltip')[0].title = this.getOption('text'); } }); export const MyView = View.extend({ template() { return [ '', 'More information' ].join(''); }, behaviors: [DestroyWarn, ToolTip] }); ``` Each behavior will now be able to respond to user interactions as though the event handlers were attached to the view directly. In addition to using array notation, Behaviors can be attached using an object: ```javascript const MyView = View.extend({ behaviors: { destroy: DestroyWarn, tooltip: ToolTip } }); ``` Arrays are the only supported list form for `behaviors`. Object maps use own enumerable string keys in standard JavaScript own-key order. Inherited, symbol, and non-enumerable properties are ignored, and a numeric `length` property is an ordinary map entry rather than an array-like signal. #### Behavior Options When we attach behaviors to views, we can also pass in options to add to the behavior. This tends to be static information relating to what the behavior should do. In our above example, we want to override the message to our `DestroyWarn` and `Tooltip` behaviors to match the original message on the View: ```javascript const MyView = View.extend({ behaviors: [ { behaviorClass: DestroyWarn, message: 'You are about to destroy all your data!' }, { behaviorClass: ToolTip, text: 'What a nice mouse you have.' } ] }); ``` There are several properties, if passed, that will be attached directly to the instance: `collectionEvents`, `events`, `modelEvents`, `stateEvents`, `triggers`, `ui` Using an object, we must define the `behaviorClass` attribute to refer to our behaviors and then add any extra options with keys matching the option we want to override. Any passed options will override the values from `options` property. Behavior options can also provide collaborators that the Behavior needs. These values are selected during construction and retained by reference. Read an arbitrary collaborator with `getOption()` so that a class default and an attachment override follow the same option precedence; arbitrary option names are not copied directly onto the Behavior instance. A host can explicitly pass an injected service through a `behaviors()` function: `initialize(options, hostView)` receives the same host View exposed as `this.view`. ```javascript import { Behavior, View } from 'marionette'; const SelectionBehavior = Behavior.extend({ initialize() { this.listenTo( this.getOption('service'), 'selection:change', this.onSelectionChange ); }, onSelectionChange(selection) { this.view.showSelection(selection); } }); export const SelectionView = View.extend({ template() { return ''; }, ui: { selection: '.selection' }, behaviors() { return [{ behaviorClass: SelectionBehavior, service: this.getOption('selectionService') }]; }, showSelection(selection) { this.getUI('selection')[0].textContent = selection.label; } }); ``` `getOption()` does not fall back to options on the host. Use `this.view` for dependencies owned by the host, such as its model or collection. A nested Behavior receives its own definition options while sharing the same host View as the Behavior that declared it. When a Behavior is removed directly or its host is destroyed, Marionette removes subscriptions created by that Behavior with `listenTo()`. It does not destroy or dispose arbitrary values passed through Behavior options, and unrelated listeners on those collaborators remain active. **Errors** An error will be thrown if the `Behavior` class is not passed. ## Nesting Behaviors In addition to extending a `View` with `Behavior`, a `Behavior` can itself use other Behaviors. The syntax is identical to that used for a `View`: ```javascript import { Behavior } from 'marionette'; const Modal = Behavior.extend({ behaviors: [ { behaviorClass: DestroyWarn, message: 'Whoa! You sure about this?' } ] }); ``` Nesting groups Behavior declarations; it does not transfer cleanup ownership to the declaring Behavior. Nested Behaviors act as direct Behaviors of the same host view, so destroying the declarer leaves them active until they are removed directly or the host is destroyed. ## The Behavior's `view` The `view` is a reference to the `View` instance that the `Behavior` is attached to. ```javascript import { Behavior } from 'marionette'; Behavior.extend({ handleDestroyClick() { this.view.destroy(); } }); ``` ## Host Communication and Event Proxies A Behavior is an event-capable object attached to one host View. It can handle host events, DOM events, and host entity events while keeping its own events separate from the host. ### Host and Behavior Events When the host calls `triggerMethod()`, the host's corresponding `onEvent` method runs first. The event is then broadcast with the same arguments to every attached Behavior, where the corresponding method runs with that Behavior as its context. Nested Behaviors participate directly in the same host broadcast. Calling the host's `trigger()` also broadcasts to Behaviors, but does not call the host's `onEvent` method. Do not rely on an ordering among Behavior handlers. Host and Behavior DOM declarations are delegated independently. If multiple Behaviors or the host declare the same event and selector, every matching declaration runs once. Do not use declaration collisions to establish precedence or suppress another handler. Host broadcasts include events produced by: * Calls to `triggerMethod()` * DOM `triggers` * `childViewTriggers` * Child events forwarded through a non-false `childViewEventPrefix` `childViewEvents` calls the configured host handler directly. It becomes a host broadcast only if that handler explicitly calls `triggerMethod()`. A call to `behavior.triggerMethod()` stays local to that Behavior. It does not invoke the host or sibling Behaviors. To request host work, call an appropriate public host method or explicitly use `this.view.triggerMethod()`. The latter is a host broadcast, so every attached Behavior receives it, including the Behavior that sent it. Do not re-emit the same host event from that Behavior's corresponding handler, as doing so would recurse. ```javascript import { Behavior, View } from 'marionette'; const SaveBehavior = Behavior.extend({ ui: { save: '.save' }, events: { 'click @ui.save': 'requestSave' }, requestSave() { this.view.requestSave(); } }); export const FormView = View.extend({ behaviors: [SaveBehavior], template() { return ''; }, requestSave() { this.triggerMethod('save:requested', this); } }); ``` Behavior DOM queries and delegation stay scoped to the host View. A matching element outside the host does not participate. Literal configuration errors fail eagerly: an undeclared `@ui` reference throws [MN0018](/docs/diagnostics.md#look-up-a-code), and a string handler that does not resolve to a callable method throws [MN0019](/docs/diagnostics.md#look-up-a-code). For example, declaring the event above without `ui.save`, or naming `requestSave` without defining that method, is invalid. A Behavior's DOM [`triggers`](/docs/dom-interactions.md#view-triggers) are emitted on the host automatically. The host method runs first, and all attached Behaviors, including the Behavior that declared the trigger, receive the broadcast. For general event naming and handler conversion, see [`triggerMethod`](/docs/events.md#triggermethod). ### Proxy Handlers Behaviors provide proxies to a number of the view event handling attributes including: * [`events`](/docs/dom-interactions.md#view-events) * [`triggers`](/docs/dom-interactions.md#view-triggers) * [`modelEvents`](/docs/entity-events.md) * [`collectionEvents`](/docs/entity-events.md) ```javascript import { Behavior } from 'marionette'; Behavior.extend({ events: { 'click .foo-button': 'onClickFooButton' }, triggers: { 'click .bar-button': 'click:barButton' }, modelEvents: { 'change': 'onChangeModel' }, collectionEvents: { 'change': 'onChangeCollection' }, onClickFooButton(evt) { // .. }, onClickBarButton(view, evt) { // .. }, onChangeModel(model, opts) { // .. }, onChangeCollection(model, opts) { // .. } }); ``` ### Initialize Order The View + Behavior initialize process is as follows: 1. View construction begins and the View's `preinitialize` runs 2. Behavior is constructed 3. Behavior is initialized with view property set 4. Callable Behavior `events` and `triggers` are resolved and delegated 5. View is initialized 6. View triggers an `initialize` event on the behavior. This means that the behavior can access the view during its own `initialize` method. It can also access state established by the View's `preinitialize` method. Callable `events` and `triggers` may use state established by that method before the View initializes. The View's `initialize` is called later with its original constructor arguments. It can observe Behavior-driven state only when a Behavior explicitly sets that state or calls a host method; Marionette does not inject Behavior information. The `initialize` event is triggered on the behavior indicating that the view is fully initialized. #### Using `ui` As in views, `events` and `triggers` can use the `ui` references in their listeners. For more details, see the [`ui` documentation](/docs/dom-interactions.md#organizing-a-view-with-ui). These can be defined on either the Behavior or the View. The fragment below assumes a Backbone model with `save()` and a configured [Backbone DataApi](/docs/backbone.md): ```javascript import { Behavior } from 'marionette'; const MyBehavior = Behavior.extend({ ui: { saveForm: '.btn-save' }, events: { 'click @ui.saveForm': 'saveForm' }, modelEvents: { invalid: 'showError' }, saveForm() { this.view.model.save(); }, showError() { alert('You have errors'); } }); ``` ### UI resolution and binding For a host whose `el` is empty at construction, the host constructs each Behavior before the host's `initialize` and before binding UI elements. During that construction, the Behavior resolves its own `ui` declaration and the host's `ui` declaration into one selector map. When both declarations contain the same key, the host's selector wins. This allows a Behavior to provide reusable defaults without dictating the host's markup. Marionette establishes this merged map before the Behavior's first DOM event and trigger delegation, so host-only keys and host overrides are available immediately. The merged selector map is available to the Behavior's `initialize`, before either the Behavior or host has bound UI elements. The map is captured for that Behavior instance during construction; later changes to values returned by a `ui` function do not replace its captured selectors. The host evaluates its own `ui` again when it binds. If a stateful host `ui` function returns a different selector then, the host binds the later selector while the Behavior continues to bind its construction-time selector. Keep `ui` functions deterministic when the host and Behavior share keys. The Behavior's `el` is also available during `initialize`. Behaviors can initialize their own `$el` wrapper with `$(this.el)` at this point. DOM event and trigger declarations are delegated only after `initialize` returns, so callable declarations may safely depend on state established there. Before binding, `behavior.ui` contains selector strings. A template-rendered `View` binds those selectors during render, after which the values are array-like element collections found only within the host's `el`. Its rerender replaces the contents and rebinds the same Behavior to the replacement elements. Code must read the current `behavior.ui` or call `behavior.getUI(name)` after binding instead of retaining an element collection from an earlier render. Calling `getUI()` without a declared `ui` map, before binding, or after unbinding throws [`MN0023`](/errors/MN0023.md). A `CollectionView` also binds Behavior UI automatically when its render processes a template. Without a template, `CollectionView#render` leaves Behavior UI as selector strings; call `collectionView.bindUIElements()` after the expected elements exist to bind them explicitly. Once the owning View or CollectionView starts destruction, its base `bindUIElements()` method and direct `bindUIElements()` calls on a Behavior owned by or retained from that host are chainable no-ops. They do not resolve host UI or query the retained root element. `unbindUIElements()` remains available for cleanup, and `getUI()` continues to throw [`MN0023`](/errors/MN0023.md) while UI is unbound. Reusing a Behavior after calling `Behavior#destroy()` while its host remains live is outside this terminal-host contract. A `View` initialized around pre-rendered content binds its own UI before it constructs Behaviors. This contract pins only that construction ordering. It intentionally leaves the mixed Behavior UI representation for that path unresolved; do not infer the selector-before-binding sequence above or rely on that representation. ```javascript import { Behavior, View } from 'marionette'; const SaveBehavior = Behavior.extend({ ui: { save: '.btn-save' }, events: { 'click @ui.save': 'requestSave' }, requestSave() { this.getUI('save')[0].classList.add('is-saving'); this.view.requestSave(); } }); export const FormView = View.extend({ behaviors: [SaveBehavior], template() { return [ '', '' ].join(''); }, ui: { save: '.btn-primary' }, requestSave() { this.triggerMethod('save:requested', this); } }); ``` ### Host DOM boundary The host View or CollectionView owns the DOM boundary for each attached Behavior. A Behavior's `el` is the host's current `el`, and its `$()` lookup delegates to the host so that results stay scoped to that element. Native core does not create `$el`. With the optional [jQuery adapter](/docs/dom-api.md#optional-jquery-adapter), application code can assign `this.$el = $(this.el)` once in `initialize()`. The host and its Behaviors keep the same root for their lifetime. Rendering can replace its contents, and `delegateEvents()` refreshes View and Behavior handlers. Destroying the host removes those handlers. Behaviors do not own or replace the root. Each Behavior can also reference its host through the `view` attribute. Read model values through the host's selected DataApi so the same code works with plain objects and configured observable providers: ```javascript import { Behavior } from 'marionette'; const ViewBehavior = Behavior.extend({ onRender() { const shouldHighlight = this.view.Data.get(this.view.model, 'selected'); this.el.classList.toggle('highlight', shouldHighlight); Array.from(this.$('.view-class')).forEach(element => { element.classList.add('highlighted-icon'); }); } }); ``` ## Behavior Lifecycle A `Behavior` has a host-managed lifetime rather than the independent rendered, attached, and destroyed state exposed by a View. In this table, the host view is either a `View` or `CollectionView`. It constructs its Behaviors, keeps the same instances through render and attachment transitions, and cleans them up when it is destroyed. Nested Behaviors participate as Behaviors of the same host view. | Operation | Host view | Behavior | | --- | --- | --- | | Construct the View | Constructs each Behavior before the View's `initialize`. | Receives its `view` and runs its own `initialize`; after the View initializes, receives the View's `initialize` notification. | | Render or re-render the View | Runs each View lifecycle callback first. | The same instance receives the corresponding lifecycle callback after the View. | | Show, detach, or re-show the host through a Region with lifecycle monitoring enabled | Changes the host's attachment state. | The same instance receives the corresponding attachment lifecycle after the host. | | First direct `behavior.destroy()` while the View is alive | Remains alive without the removed Behavior. | Undelegates its events, stops listening, removes itself from the View, and deletes its entity-event handlers. It receives no later host lifecycle notifications. | | Destroy the View | Runs `before:destroy`, tears down the View, and runs its `destroy` callback. Repeated View destruction is a no-op. | Receives `before:destroy` while the View is alive, is cleaned up after the View enters destroyed, then receives `destroy` after the View's callback. Nested Behaviors follow the same ordering. | `Behavior` does not expose an independent `isDestroyed()` state. Repeated direct `behavior.destroy()` calls, reuse after direct cleanup, and other post-cleanup operations are outside this lifecycle contract. Dependency access, invalid references, and dynamic replacement semantics are separate Behavior contract decisions; this table does not add an Application or State lifecycle to Behavior. If a Region's owning view sets `monitorViewEvents: false`, the shown host does not receive attachment lifecycle notifications, so its Behaviors do not receive them either. Separately, setting `monitorViewEvents: false` on the host itself does not by itself suppress Region attachment lifecycle. It suppresses the host's `dom:refresh` and `dom:remove` notifications, so its Behaviors do not receive those notifications. ## Destroying a Behavior `myBehavior.destroy()` synchronously returns the Behavior after removing its DOM and entity subscriptions, releasing its State subscriptions and owned State, calling `stopListening()`, and removing it from the host. It does not emit an independent destroy lifecycle or await Promises. Errors propagate and can leave cleanup incomplete; the host itself remains alive. [Canonical source](/docs/markdown/docs/marionette.behavior.md) · [Source identity](/docs/manifest.json) --- Document: docs/view.lifecycle.md Canonical URL: https://marionettejs.com/docs/lifecycle/ Markdown URL: https://marionettejs.com/docs/lifecycle.md Reading SHA-256: 978b05fb72fbffe2d124f1e257cb7d9b06cb66a28f1d339f61ef074888120080 # View Lifecycle Both [`View` and `CollectionView`](/docs/classes.md) are aware of their lifecycle state which indicates whether the View is rendered, attached, or destroyed. ## Documentation Index * [View Lifecycle](#view-lifecycle) * [Lifecycle State Methods](#lifecycle-state-methods) * [`isRendered()`](#isrendered) * [`isAttached()`](#isattached) * [`isDestroyed()`](#isdestroyed) * [Instantiating a View](#instantiating-a-view) * [A fixed root element](#a-fixed-root-element) * [Rendering a View](#rendering-a-view) * [`View` Rendering](#view-rendering) * [`CollectionView` Rendering](#collectionview-rendering) * [Rendering Children](#rendering-children) * [Attaching a View](#attaching-a-view) * [Detaching a View](#detaching-a-view) * [Destroying a View](#destroying-a-view) * [Synchronous failures](#synchronous-failures) * [Destroying Children](#destroying-children) ## Lifecycle State Methods Both `View` and `CollectionView` share methods for checking lifecycle state. ### `isRendered()` Returns a boolean value reflecting if the view is considered rendered. ### `isAttached()` Returns a boolean value reflecting if the view is considered attached to the DOM. ### `isDestroyed()` Returns a boolean value reflecting if the view has been destroyed. ### State vectors The three lifecycle methods are independent observations, not one linear state enum. `View` construction can therefore produce any of the four alive render/attachment vectors: | Initial `el` | `isRendered()` | `isAttached()` | `isDestroyed()` | | --- | --- | --- | --- | | Empty and detached | `false` | `false` | `false` | | Empty and in the document | `false` | `true` | `false` | | Populated and detached | `true` | `false` | `false` | | Populated and in the document | `true` | `true` | `false` | `CollectionView` starts unrendered regardless of its initial contents and has its own [lifecycle transition table](/docs/collection-view.md#view-lifecycle-and-events). With lifecycle monitoring enabled, Marionette-managed operations preserve the following observable transitions: | Operation | Result | Repeated call | | --- | --- | --- | | `View#render()` with a template function while alive | Runs `before:render` and `render`; rendered becomes `true`; attachment is unchanged | Renders again and runs the render lifecycle again | | `View#render()` with `template: false` while alive | Returns the View without running the render lifecycle or changing contents or state | Repeated calls are the same no-op | | `CollectionView#render()` while alive | Runs `before:render` and `render`, rebuilds its children, and becomes rendered; attachment is unchanged | Rebuilds the children and runs the render lifecycle again | | `view.renderAttributes()` while alive | Applies the current root attribute declarations without changing contents, children, lifecycle events, or state | Reevaluates and applies the declarations again | | `region.show(view)` | Ensures the view is rendered; attached becomes `true` only when the Region is in the document | Showing the current view is a no-op | | `region.detachView()` | Rendered is preserved; attached becomes `false`; destroyed stays `false` | Returns `undefined` with no transition | | Re-show a detached view | Rendered stays `true`; attachment reflects the Region | Does not render the view again | | `region.empty()` or `view.destroy()` | Rendered and attached become `false`; destroyed becomes `true` | Repeated destroy is a no-op | | `view.render()` after destruction | Returns the same View with rendered and attached `false` and destroyed `true` | Repeated calls are no-ops | | `view.renderAttributes()` once destruction begins | Returns the same View before resolving declarations or changing the root element or lifecycle state | Repeated calls are no-ops | | `CollectionView#addChildView(view, ...)` once destruction begins | Returns the supplied child before inspecting or taking ownership of it; the caller remains responsible for that child | Repeated calls are no-ops for the destroyed CollectionView | | `view.delegateEvents()` or `view.undelegateEvents()` once destruction begins | Returns the same View without changing View or Behavior DOM delegation | Repeated calls are no-ops | | `view.bindUIElements()` once destruction begins | Returns the same View without resolving host UI, querying DOM, or binding View or Behavior UI | Repeated calls are no-ops | Setting `monitorViewEvents: false` on a Region's owning view intentionally disables attachment events and automatic `isAttached()` updates for the shown view. This table specifies the managed and terminal operations listed above. Do not infer behavior for other calls on a destroyed View; custom overrides also own their behavior unless they delegate to a guarded base method. ## Instantiating a View Every Marionette `View` and `CollectionView` has a native DOM element in `el`. Pass an existing element with `el: document.querySelector('.foo-selector')`, or create one first with `document.createElement()`. Selector strings and jQuery collections are not valid View `el` values. When `el` is omitted, Marionette creates the root element from `tagName` (a `div` by default) and applies the resolved `id`, `className`, and `attributes`. The element remains the View's root for its entire lifetime. Native core does not create `$el`; applications can initialize their own wrapper when using the [jQuery adapter](/docs/dom-api.md#optional-jquery-adapter). Marionette determines whether the initial root is already [rendered](#rendering-a-view) or [attached](#attaching-a-view). If a View starts rendered or attached, its [state](#lifecycle-state-methods) reflects that status, but the [related events](/docs/class-events.md#dom-change-events) will not have fired. An element owned by template content is detached while that owner document has no document element. Showing its View later through an attached Region runs the managed attachment lifecycle once for the View and its existing children. For more information on instantiating a view with pre-rendered DOM, see [Pre-rendered Content](/docs/prerendered-dom.md). ### A fixed root element Choose the root with the constructor's `el` option, or let Marionette create it. A View and its Behaviors keep that element for their lifetime. `el` is readonly in the public instance types; assigning another element directly is unsupported. There is no public `setElement()` method. Rendering changes the root's contents. Moving or detaching a View through a Region preserves its root and its child ownership. If another system replaces the root, destroy the old View and construct a new View with the new element. Keep state that must survive that replacement outside the View. ## Rendering a View In Marionette [rendering a view](/docs/rendering.md) is changing a view's `el`'s contents. What rendering indicates varies slightly between the two Marionette views. **Note** A completed render leaves the View rendered until destruction. During a normalized collection update, CollectionView may mark an updated child unrendered before rendering it again; a filtered child can remain unrendered until it becomes visible. ### `View` Rendering For [`View`](/docs/view.md), rendering with a template function runs the `before:render` lifecycle, serializes the View's data, passes it to the template, places the result in `el`, binds UI, marks the View rendered, and then runs the `render` lifecycle. A newly constructed `View` is already considered rendered if its initial `el` contains content. A later template may produce empty content; the completed render still leaves the View rendered. `template: false` is different from a template that returns an empty value. Calling `View#render()` with `template: false` returns the View without running the render lifecycle, changing the DOM, or changing its rendered state. ### `CollectionView` Rendering For [`CollectionView`](/docs/collection-view.md), every live `render()` is bracketed by `before:render` and `render`. After it completes, collection-backed children have been rebuilt, the optional template and visible children have been rendered, and the CollectionView is rendered. Any children the CollectionView owned before that render have been destroyed. Inserting a child element into the CollectionView is not itself an attachment transition. When the CollectionView is monitored as attached, rendering marks and notifies the inserted children as attached; when the parent is detached or child lifecycle monitoring is disabled, their monitored attachment state remains detached even though their elements are inside the parent element. A CollectionView with no children is still rendered, with or without an [`emptyView`](/docs/collection-view.md#collectionviews-emptyview). Its own template controls the container markup but does not determine rendered state. ## Rendering Children Rendering child views is often best accomplished after the View renders, as the first render typically happens before the View enters the DOM. This helps to prevent unnecessary repaints and reflows by making the DOM insertion at the highest practical View in the view tree. The exception is Views with [pre-rendered content](/docs/prerendered-dom.md). When a View is instantiated rendered, child Views are best managed in the View's [`initialize`](/docs/common.md#initialize). ### `View` Children In general the best method for adding a child view to a `View` is to use [`showChildView`](/docs/view.md#showing-a-child-view) in the [`render` event](/docs/class-events.md#render-and-beforerender-events). View Regions are emptied on each render, so Views shown outside of the `render` event still need to be shown again on subsequent renders. ### `CollectionView` Children The primary use case for a `CollectionView` is maintaining collection-backed child Views. Marionette creates and removes those children as the collection changes. `addChildView()` can also add a child that is independent of the collection, but that child is not unmanaged. The CollectionView owns it, includes it in its child containers, and may sort or filter it. Rendering, collection reset, or CollectionView destruction destroys every child that is still owned, including manually added children. `detachChildView()` is the explicit operation that removes a child from ownership without destroying it and transfers cleanup responsibility to the caller. See [Self-Managed `children`](/docs/collection-view.md#self-managed-children) for the supported add, remove, detach, sorting, and filtering contracts. ## Attaching a View `isAttached()` is Marionette's monitored lifecycle state, not a live query of the physical DOM on every call. Construction initializes it from the current root element, and Marionette-managed Region and CollectionView operations update it while attachment monitoring is enabled. The [`attach` event](/docs/class-events.md#attach-and-beforeattach-events) is the appropriate place to add listeners to the root `el`. Render can replace the contents while that root remains attached; use [`dom:refresh`](/docs/class-events.md#domrefresh-event) for listeners tied to those rendered descendants. Moving `view.el` directly with native DOM APIs, such as `document.body.append(view.el)`, changes its physical location without running Marionette attachment lifecycles or updating `isAttached()`. The same caveat applies when application code directly removes or moves an attached root. Prefer a Region or CollectionView for managed transitions; if application code moves the element directly, it owns the resulting lifecycle mismatch. A child shown in a rendered but detached parent View's Region is rendered and remains detached. When the parent is later shown in an attached Region, attachment propagates to its existing children. A child shown during the parent's `onAttach` is attached immediately. Showing the same attached parent again is a no-op for both parent and child attachment lifecycles. ## Detaching a View A managed View becomes detached when Marionette removes its `el` from the DOM and updates its monitored attachment state. Use the [`before:detach` event](/docs/class-events.md#detach-and-beforedetach-events) to clean up listeners added to the root `el`. Render can replace descendants while the root remains attached; use [`dom:remove`](/docs/class-events.md#domremove-event) to clean up listeners tied to those rendered descendants. Detaching a parent View propagates detachment to its managed Region children while preserving their rendered state and ownership. Re-showing that parent attaches the same children again. Emptying the parent-owning Region then detaches and destroys the parent and its still-managed children once. ## Destroying a View Destroying a View (for example, `myView.destroy()`) removes Marionette-owned resources: delegated View and Behavior DOM handlers, bound UI, outgoing `listenTo()` subscriptions, entity-event bookkeeping, Behaviors, Regions and their current Views, and CollectionView children that remain owned. It detaches the root element and leaves the View rendered `false`, attached `false`, and destroyed `true` after successful teardown. Destroy does not remove callbacks registered directly on the View with `on()`, destroy its model, collection, or arbitrary option collaborators, or clean up application resources Marionette does not own. Release those resources in the appropriate lifecycle callback. The [`before:destroy` event](/docs/class-events.md#destroy-and-beforedestroy-events) is the best place to clean up any added listeners not related to the view's DOM. Once destruction begins, reentrant `destroy()` calls from `before:destroy` or `destroy`, and later repeated calls, return the same View without restarting teardown. During a normal successful teardown, an attached parent and its owned children complete their detach and destroy lifecycles once. Base `View#bindUIElements()` and `CollectionView#bindUIElements()` calls are also terminal no-ops once destruction begins. They do not resolve callable UI, query the retained root element, or bind attached Behaviors. A direct `Behavior#bindUIElements()` call through a Behavior owned by or retained from that host returns the Behavior without binding. `unbindUIElements()` remains available for cleanup, and `getUI()` continues to throw `MN0023` when UI is unbound. Errors from lifecycle handlers propagate and stop the operation, as described under [Synchronous failures](#synchronous-failures). A throwing `before:destroy` or later cleanup handler does not clear the destruction guard or make a later `destroy()` call resume teardown. Successful destruction retains the root `el` object but detaches it. Do not infer that all of its contents are retained: owned child Views are removed as they are destroyed, and Region or CollectionView cleanup can detach contents from managed containers. Marionette makes no general cleanup promise for unowned DOM outside those managed boundaries. ## Synchronous failures Marionette expects valid adapters and working registration and cleanup callbacks. An exception during synchronous registration, construction, rendering, or teardown propagates to the caller and aborts that operation. Completed work is not rolled back. Marionette does not promise to release every resource after a callback throws, restore a partially initialized or rendered instance, or recover on the next call or source notification. Fix the failing callback or adapter; do not rely on partial instance state after a failure. Successful cleanup and the documented ownership and repeated-destruction rules still apply. A callback that destroys or mutates an owner during an in-progress render does not acquire additional recovery guarantees merely because it calls a public method; use the documented lifecycle boundaries for that workflow. Application's [asynchronous lifecycle](/docs/application.md#application-lifecycle) has its own readiness, cancellation, rejection, and restart semantics. This synchronous failure boundary does not replace those contracts or change ordinary supersession into an error. ## Destroying Children Children still owned by a View's Region or a CollectionView are automatically destroyed when their owner completes a re-render or is destroyed. A CollectionView also destroys its currently owned children when its collection is reset before building the replacement collection-backed children. A child returned by `detachView()` or `detachChildView()` is no longer owned and is not included in later owner cleanup. During owner destruction, children are removed after the parent root is detached to avoid repeated reflows or repaints. [Canonical source](/docs/markdown/docs/view.lifecycle.md) · [Source identity](/docs/manifest.json) --- Document: docs/view.rendering.md Canonical URL: https://marionettejs.com/docs/rendering/ Markdown URL: https://marionettejs.com/docs/rendering.md Reading SHA-256: 8214bfbec96f34c818764430b042fe18b18094ed6ba0d4e7c488de020b6a3877 # View Template Rendering Give a view a template function, then call `render()` to put its result in the view's element. A plain function is enough to get started; template engines and custom renderers can fit the same workflow. The renderer evaluates the template; DomApi applies the result to the element. Projects can configure template evaluation with `setRenderer()` directly. Lit and Morphdom are DOM adapters configured with `setDomApi()`. ```javascript import { View } from 'marionette'; const MyView = View.extend({ tagName: 'h1', template: () => 'Contents' }); const myView = new MyView(); myView.render(); ``` This renders `

Contents

`, available at `myView.el`. ## Documentation Index * [What is a template](#what-is-a-template) * [Setting a View Template](#setting-a-view-template) * [Using a View Without a Template](#using-a-view-without-a-template) * [Rendering the Template](#rendering-the-template) * [Using a Custom Renderer](#using-a-custom-renderer) * [Rendering to HTML](#rendering-to-html) * [Rendering to DOM](#rendering-to-dom) * [Serializing Data](#serializing-data) * [Serializing a Model](#serializing-a-model) * [Serializing a Collection](#serializing-a-collection) * [Serializing with a `CollectionView`](#serializing-with-a-collectionview) * [Adding Context Data](#adding-context-data) * [What is Context Data?](#what-is-context-data) ## What is a template? A template is a function that given data returns either an HTML string or DOM. [The default renderer](#rendering-the-template) in Marionette expects the template to return an HTML string. If your application uses Underscore, its [template compiler](http://underscorejs.org/#template) can create that function. Install Underscore as an application dependency to use the following example; Marionette does not include it. ```javascript import _ from 'underscore'; import { View } from 'marionette'; const MyView = View.extend({ template: _.template('

Hello, world

') }); ``` This doesn't have to be an underscore template, you can pass your own rendering function: ```javascript import Handlebars from 'handlebars'; import { View } from 'marionette'; const MyView = View.extend({ template: Handlebars.compile('

Hello, {{ name }}

') }); ``` ## Setting a View Template Marionette views use the `getTemplate` method to determine which template to use for rendering into its `el`. By default `getTemplate` is predefined on the view as simply: ```javascript getTemplate() { return this.template } ``` In most cases by using the default `getTemplate` you can simply set the `template` on the view to define the view's template, but in some circumstances you may want to set the template conditionally. ```javascript import _ from 'underscore'; import { View } from 'marionette'; const MyView = View.extend({ template: _.template('Hello World!'), getTemplate() { if (this.Data.has(this.model, 'user')) { return _.template('Hello User!'); } return this.template; } }); ``` ### Using a View Without a Template By default `CollectionView` has no defined `template` and will only attempt to render the `template` if one is defined. For `View` there may be some situations where you do not intend to use a `template`. Perhaps you only need the view's `el` or you are using [prerendered content](/docs/prerendered-dom.md). In this case setting `template` to `false` will prevent the template render. In the case of `View` it will also prevent the [`render` events](/docs/class-events.md#render-and-beforerender-events). ```javascript import { View } from 'marionette'; const MyIconButtonView = View.extend({ template: false, tagName: 'button', className: 'icon-button', triggers: { 'click': 'click' }, onRender() { console.log('You will never see me!'); } }); ``` ## Rendering the Template Each view class has a renderer which by default passes the [view data](#serializing-data) to the template function and returns the html string it generates. The current default renderer is essentially the following: ```javascript import { View, CollectionView } from 'marionette'; function renderer(template, data) { return template(data); } View.setRenderer(renderer); CollectionView.setRenderer(renderer); ``` The default expects a function template; it does not look up script elements by selector. ### Using a Custom Renderer You can set the renderer for a view class by using the class method `setRenderer`. The renderer accepts two arguments. The first is the template passed to the view, and the second argument is the data to be rendered into the template. Marionette invokes the renderer with the View as `this`, so use a regular function when the renderer needs access to the View instance. Rendering is synchronous. A renderer must return content supported by the chosen DomApi immediately; returning a Promise does not make `render()` await it. Complete asynchronous loading before rendering, or update the View when the result becomes available under its owner's cancellation rules. Marionette passes the renderer's return value to [`attachElContent`](#customizing-attachelcontent), which calls `Dom.setContents`. The renderer evaluates the template; the DOM adapter applies its result. The native, jQuery, and Morphdom adapters treat `null` and `undefined` as empty contents. Lit accepts these values as empty content too. Returning `undefined` does not bypass content attachment. Here's an example that allows for the `template` of a view to be an underscore template string. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import _ from 'underscore'; import { setDataApi, View } from 'marionette'; setDataApi(BackboneApi); View.setRenderer(function(template, data) { return _.template(template)(data); }); const myView = new View({ template: 'Hello <%- name %>!', model: new Backbone.Model({ name: 'World' }) }); myView.render(); // myView.el is
Hello World!
``` The renderer can also be customized separately on any extended View. This standalone example uses the default plain-object DataApi and requires the application to install Handlebars. ```javascript import Handlebars from 'handlebars'; import { View } from 'marionette'; const MyHBSView = View.extend(); // Similar example as above but for handlebars MyHBSView.setRenderer(function(template, data) { return Handlebars.compile(template)(data); }); const myHBSView = new MyHBSView({ template: 'Hello {{ name }}!', model: { name: 'World' } }); myHBSView.render(); // myHBSView.el is
Hello World!
``` **Note** These examples while functional may not be ideal. If possible it is recommended to precompile your templates which can be done for a number of templating engines using various plugins for bundling tools such as [Browserify or Webpack](/docs/installation.md). ### Rendering to HTML The default Marionette renderer returns the HTML as a string. This string is passed to the view's `attachElContent` method which in turn uses the DOM API's [`setContents`](/docs/dom-api.md#setcontentsel-html) to set the contents of the view's `el` with DOM from the string. #### Customizing `attachElContent` You can modify the way any particular view attaches a compiled template to the `el` by overriding `attachElContent`. This method always receives the result of the view's renderer, including `undefined`. For instance, perhaps for one particular view you need to bypass the [DOM API](/docs/dom-api.md) and set the html directly: ```javascript attachElContent(html) { this.Dom.setContents(this.el, html); } ``` ### Rendering to DOM A DOM adapter can update existing content incrementally. The optional `@mnjs/adapters` package includes Morphdom and Lit HTML integrations. Install only the DOM adapter peer your application uses and configure a View subclass before creating its instances. `setDomApi` overlays the supplied methods and preserves unrelated operations, including jQuery queries. For HTML string templates: ```javascript import { View } from 'marionette'; import MorphdomDomApi from '@mnjs/adapters/dom/morphdom'; const MessageView = View.extend({ template: () => '

Hello again.

' }); MessageView.setDomApi(MorphdomDomApi); ``` Morphdom updates the View's contents using its normal matching rules, including element IDs. Empty roots take the direct HTML insertion path. For Lit templates, select the Lit DOM adapter: ```javascript import { View } from 'marionette'; import { html } from 'lit-html'; import LitDomApi from '@mnjs/adapters/dom/lit-html'; const MessageView = View.extend({ template: ({ message }) => html`

${message}

`, templateContext: { message: 'Hello again.' } }); MessageView.setDomApi(LitDomApi); ``` Both adapters apply template output through `Dom.setContents`. The root remains owned by the View; refresh its dynamic `className`, `id`, or `attributes` with [`renderAttributes()`](/docs/view.md#refreshing-root-attributes). A parent render still destroys its Region children. Keep Region placeholders empty so the renderer and Region do not manage the same contents. Lit replaces preexisting contents on its first explicit render. Keep `monitorViewEvents` enabled and manage attachment through Regions so directives receive connection changes through `Dom.notifyAttach(el)` and `Dom.notifyDetach(el)`. The View keeps the same root throughout its lifetime. Automatic directive connection management requires monitoring on the View and its ancestors. Lifecycle overrides must call their parent methods; avoid independently replacing Lit's contents or switching DOM adapters after rendering. See the [render adapter guide](/docs/adapters-package.md#dom-contents) for installation, directive cleanup, and root ownership. Rendering configuration is separate from data and state integration. Configure [`DataApi`](/docs/data-api.md) and [`StateApi`](/docs/state.md) explicitly when your sources need them. ## Serializing Data Marionette will automatically serialize the data from its `model` or `collection` through the configured [`DataApi`](/docs/data-api.md) for the template to use at [rendering](#rendering-the-template). You can override this logic and provide serialization of other data with the `serializeData` method. The method is called with no arguments, but has the context of the view and should return a javascript object for the template to consume. If `serializeData` does not return data the template may still receive [added context](#adding-context-data) or an empty object for rendering. ```javascript import _ from 'underscore'; import { View } from 'marionette'; const MyView = View.extend({ template: _.template(`
<%- user.name %>
`), serializeData() { // For this view I need both the // model and collection serialized return { user: this.serializeModel(), groups: this.serializeCollection(), }; } }); ``` **Note** You should not use this method to add arbitrary extra data to your template. Instead use `templateContext` to [add context data to your template](#adding-context-data). ### Serializing a Model If the view has a `model`, it passes `DataApi.serialize(model)` to the template. The default adapter returns the original plain object. ```javascript import _ from 'underscore'; import { View } from 'marionette'; const MyView = View.extend({ template: _.template('

Hello, <%- name %>

') }); const myView = new MyView({ model: { name: 'world' } }); ``` How the `model` is serialized can also be customized per view. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import _ from 'underscore'; import { setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const MyView = View.extend({ serializeModel() { const data = _.clone(this.Data.serialize(this.model)); // serialize a nested Backbone model through the configured adapter data.subModel = this.Data.serialize(data.subModel); return data; } }); ``` ### Serializing a Collection If the view does not have a `model` but has a `collection`, DataApi supplies its ordered models and serializes each one into an array provided as a `models` attribute to the template. These are the results of calling `DataApi.serialize()` for each model, not the raw model instances returned by `DataApi.models()`. ```javascript import _ from 'underscore'; import { View } from 'marionette'; const MyView = View.extend({ template: _.template(` `) }); const collection = [ {name: 'Steve'}, {name: 'Helen'} ]; const myView = new MyView({ collection }); ``` How the `collection` is serialized can also be customized per view. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import _ from 'underscore'; import { setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const MyView = View.extend({ serializeCollection() { return _.map(this.Data.models(this.collection), model => { const data = _.clone(this.Data.serialize(model)); // serialize a nested Backbone model through the configured adapter data.subModel = this.Data.serialize(data.subModel); return data; }); } }); ``` ### Serializing with a `CollectionView` If you are using a `template` with a `CollectionView` that is not also given a `model`, your `CollectionView` will [serialize the collection](#serializing-a-collection) for the template. This could be costly and unnecessary. If your `CollectionView` has a `template` it is advised to either use an empty `model` or override the [`serializeData`](#serializing-data) method. ## Adding Context Data Marionette views provide a `templateContext` attribute that is used to add extra information to your templates. This can be either an object, or a function returning an object. The keys on the returned object will be mixed into the model or collection keys and made available to the template. When serialized data and template context are combined, each contributes its own enumerable properties, including symbols, through object spread. Inherited and non-enumerable properties are ignored. If only one object exists, Marionette passes that original object through unchanged. ```javascript import _ from 'underscore'; import { View } from 'marionette'; const MyView = View.extend({ template: _.template('

Hello, <%- name %>

'), templateContext: { name: 'World' } }); ``` Additionally context data overwrites the serialized data ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import _ from 'underscore'; import { setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const MyView = View.extend({ template: _.template('

Hello, <%- name %>

'), templateContext() { return { name: this.Data.get(this.model, 'name').toUpperCase() }; } }); ``` You can also define a template context value as a method. How this method is called is determined by your templating solution. For instance with handlebars a method is called with the context of the data passed to the template. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Handlebars from 'handlebars'; import Backbone from 'backbone'; import { setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const MyView = View.extend({ template: Handlebars.compile(` Hello {{ fullName }}, `), templateContext: { isDr() { return (this.degree) === 'phd'; }, fullName() { // Because of Handlebars `this` here is the data object // passed to the template which is the result of the // templateContext mixed with the serialized data of the view return this.isDr() ? `Dr. ${this.name}` : this.name; } } }); const myView = new MyView({ model: new Backbone.Model({ degree: 'masters', name: 'Joe' }) }); ``` **Note** the data object passed to the template is not deeply cloned and in some cases is not cloned at all. Take caution when modifying the data passed to the template, that you are not also modifying your model's data indirectly. ### What is Context Data? While [serializing data](#serializing-data) deals more with getting the data belonging to the view into the template, template context mixes in other needed data, or in some cases, might do extra computations that go beyond simply "serializing" the view's `model` or `collection`. This fragment assumes an application-specific Backbone model with `getOrganization()` and `getFullName()` methods, and a Backbone collection of groups; these helpers are not Marionette APIs. ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import _ from 'underscore'; import { CollectionView, setDataApi } from 'marionette'; import GroupView from './group-view'; setDataApi(BackboneApi); const MyCollectionView = CollectionView.extend({ tagName: 'div', childViewContainer: 'ul', childView: GroupView, template: _.template(`

Hello <%- name %> of <%- orgName %>

You have <%- stats.public ?? 0 %> group(s).
You have <%- stats.private ?? 0 %> group(s).

Groups:

    `), templateContext() { const user = this.model; const organization = user.getOrganization(); const groups = this.collection; return { orgName: organization.get('name'), name: user.getFullName(), stats: groups.countBy('type') }; } }) ``` [Canonical source](/docs/markdown/docs/view.rendering.md) · [Source identity](/docs/manifest.json) --- Document: docs/dom.interactions.md Canonical URL: https://marionettejs.com/docs/dom-interactions/ Markdown URL: https://marionettejs.com/docs/dom-interactions.md Reading SHA-256: 88731d52fd2f5ab76a53e14ee260c90a6a7a46b52d1d37d3297fddde44062095 # DOM Interactions Marionette `View` and `CollectionView` instances manage DOM interactions through a root DOM element, `el`. Core uses the browser DOM API by default: `view.$()` and bound `getUI()` values are native `NodeList` instances, and delegated handlers receive native DOM events. `View`, `CollectionView`, and `Behavior` use the public EventDelegator runtime adapter described below. Core provides a native DOM adapter by default. ## DOM Ownership Boundaries Use these boundaries when deciding where DOM work belongs: * The external shell chooses where a root View is mounted. Pass a concrete DOM element as `el`, or append the View's generated `el` to the shell's mount. * A View owns its `el` and the nodes produced by its template. * A Behavior borrows its host View's DOM boundary. It does not own a separate root; see [Behavior host communication](/docs/behavior.md#host-communication-and-event-proxies). * The external shell or owning View owns the DOM element used as a Region mount. The Region manages the placement and lifecycle of its current child View at that mount. Use the [View Region APIs](/docs/view.md#laying-out-views---regions) to show, access, detach, or empty that child. * A child View owns its own `el` and handles interactions inside it. DOM scoping is structural, not ownership-aware. `view.$()`, `ui`, and delegated selectors are rooted at `view.el`, so they exclude matching elements outside that root. They can still match a descendant owned by a child View. Do not use a parent query such as `parentView.$('.child-control')` to manipulate child-owned DOM. Give each owner distinct selectors and communicate across View boundaries through public View or Region APIs and [explicit child events](/docs/events.md#child-view-events). ## Canonical View Interaction The example below defines selectors once in `ui`, handles a save click through `events`, and translates a close click into the `form:close` View event through `triggers`. ```javascript import { View } from 'marionette'; export const FormView = View.extend({ template() { return `
    `; }, ui: { save: '.save', close: '.close' }, events: { 'click @ui.save': 'onSave' }, triggers: { 'click @ui.close': 'form:close' }, onSave(event) { const [saveButton] = this.getUI('save'); saveButton.disabled = true; this.triggerMethod('form:save', this, event); }, onFormClose(view) { view.el.dataset.closed = 'true'; } }); ``` Create and render the View before accessing its bound UI elements: ```javascript const formView = new FormView(); formView.render(); document.querySelector('#form-host').append(formView.el); ``` The shell owns `#form-host`; `formView` owns the generated `formView.el` inside it. Destroy the View when the shell is finished with it so delegated handlers and other owned resources are cleaned up. ## View `events` The `events` attribute delegates DOM events from the View's `el` to functions or methods on the View. A key has this shape: ```javascript ' [CSS selector]': 'methodName' ``` The CSS selector is optional. Without one, the handler is bound to the View's root `el`. Use `@ui.` in place of a literal selector to reference a declared `ui` key, as the canonical example does with `@ui.save`. The handler receives the native DOM event as its first argument and runs with the View as its context. An `events` value must be a function or a string that resolves to a callable method. Invalid handlers throw `MarionetteError` with code [`MN0019`](/errors/MN0019.md) before Marionette delegates any handler from that event map. Delegation sees matching descendants throughout `el`. If a child View contains the same selector, its bubbling DOM event can reach the parent handler. Prefer owner-specific selectors; use Marionette events for parent-child communication instead of relying on DOM bubbling across ownership boundaries. Call `view.delegateEvents(events)` to refresh delegated DOM handlers after changing a callable `events` or `triggers` definition. UI references use the View's current selector bindings; a Behavior retains the selector map captured at construction, as described in [Behavior UI resolution](/docs/behavior.md#ui-resolution-and-binding). A supplied event map replaces only the View's configured `events` for that delegation pass; View triggers and Behavior events and triggers remain active. The method first removes existing handlers, so repeated calls do not duplicate them. `view.undelegateEvents()` removes the View and Behavior DOM handlers. Both methods return the View, and both are no-ops after destruction has started. Construction calls `delegateEvents()`. A subclass override remains responsible for delegating to the base method when it wants Marionette's cleanup and redelegation. ## EventDelegator Adapter An EventDelegator owns how one normalized `events` or `triggers` declaration is registered and removed. Marionette still owns declaration resolution, handler context, UI normalization, and the timing of registration and cleanup. Configure every View, CollectionView, and Behavior class with the root setter: ```javascript import { setEventDelegator } from 'marionette'; setEventDelegator(MyEventDelegator); ``` Or configure one class hierarchy through its static setter: ```javascript const InstrumentedView = View.extend({}); InstrumentedView.setEventDelegator(MyEventDelegator); ``` The supplied object is a complete adapter, not a partial overlay. It must provide this method. This example retains native selector and focus behavior; an instrumentation adapter could record around the same registration: ```javascript export const CustomEventDelegator = { delegate({ eventName, selector, handler, rootEl }) { const capture = eventName === 'focus' || eventName === 'blur'; const listener = selector ? event => { const target = event.target.nodeType === 1 ? event.target : event.target.parentElement; const match = target && target.closest(selector); if (match && match !== rootEl && rootEl.contains(match)) { event.delegateTarget = match; return handler(event); } } : handler; rootEl.addEventListener(eventName, listener, capture); return () => rootEl.removeEventListener(eventName, listener, capture); } }; ``` The arguments are: * `eventName`: the first token in the declaration key. Begin the key with the event name, without leading whitespace. * `selector`: the remaining selector, or an empty string for a direct handler. * `handler`: Marionette's normalized callback. The adapter must preserve its arguments and return behavior. * `rootEl`: the View or CollectionView's current `el`. A Behavior receives its host View's current `el`. `delegate` must return an idempotent cleanup function that removes exactly the registration it created, including its original root, listener, namespace, and capture/options policy. Marionette owns and stores that opaque cleanup. The adapter must not mutate View internals. Marionette invokes the returned cleanups during redelegation or destruction, in reverse registration order. Registration and cleanup errors propagate to the caller and stop the operation. Core does not roll back failed registration or attempt remaining cleanup after a callback throws. See the shared [synchronous failure boundary](/docs/lifecycle.md#synchronous-failures). `setEventDelegator` requires an adapter with a callable `delegate` method. Each registration must return a working cleanup. The TypeScript contract checks these shapes; core trusts the configured adapter. Adapter selection occurs at registration time. Changing a global or per-class adapter does not reinterpret existing registrations; their original opaque cleanups remain authoritative. The newly configured adapter is used the next time declarations are delegated, including a new instance, an explicit `delegateEvents()` call. A per-class setter creates an own adapter override for that class hierarchy, so a later root setter does not replace it. The native adapter uses `addEventListener`. Selector declarations walk from a text or element target to the closest matching descendant of `rootEl` and set `event.delegateTarget` to that match. Native event names are literal: namespaces such as `click.menu` are not interpreted, and non-bubbling events such as `mouseenter` are not emulated. Delegated native `focus` and `blur` use capture because those events do not bubble. The delegated handler therefore runs before a target-element listener. A Marionette trigger stops propagation by default, which prevents the event from reaching that target listener. Set `stopPropagation: false` on that trigger when the target must also observe the focus or blur event; the Marionette trigger still runs first. Marionette does not silently translate these declarations to `focusin` or `focusout`. A jQuery adapter can implement the same protocol with paired `.on()` and `.off()` calls. Compatibility tests exercise that protocol, but v5 does not yet ship a jQuery EventDelegator. A custom adapter is needed only when the application requires jQuery-specific namespaces, programmatic dispatch, and delegated focus behavior without adding jQuery to the core production graph. React and Vue normally own events within the subtree they render; integrate those subtrees through explicit DOM and lifecycle ownership boundaries instead of replacing Marionette's EventDelegator with a React or Vue adapter. ## View `triggers` The `triggers` attribute translates a DOM event into a Marionette View event. In the canonical example, clicking the close button emits exactly `form:close`. Listeners and the matching `onFormClose` method receive the triggering View first, followed by the native DOM event. By default, a trigger calls `preventDefault()` and `stopPropagation()` on the DOM event. Configure either behavior for one trigger with an object: ```javascript triggers: { 'click @ui.close': { event: 'form:close', preventDefault: true, stopPropagation: false } } ``` These settings are local to the configured trigger. Selectors remain scoped only by the View's root `el`. For a child owned through a Region, automatic parent handling and forwarding is opt-in. `childViewEvents` calls a configured parent handler, `childViewTriggers` re-emits a configured parent event, and a non-false `childViewEventPrefix` forwards prefixed events. A parent may instead subscribe directly with public [`listenTo(childView, ...)`](/docs/events.md#listening-to-events), but that is an explicit subscription rather than automatic bubbling. See [Child View Events](/docs/events.md#child-view-events) for the configured contracts. ## Organizing a View with `ui` The `ui` attribute gives frequently used CSS selectors stable names: ```javascript ui: { save: '.save', close: '.close' } ``` When Marionette iterates a UI definition for binding, or a map passed to a UI normalization helper, it uses own enumerable string keys in standard JavaScript own-key order. Inherited, symbol, and non-enumerable properties are ignored by those iterations, and a numeric `length` is an ordinary key rather than an array-like signal. Arrays, sparse arrays, and other array-like values are not supported as UI maps. A literal own `__proto__` key remains an own entry in normalized and bound UI maps without changing either map's prototype. Direct `@ui.` lookup follows the own-declaration contract described below and does not require the declared selector property to be enumerable. When the View renders, Marionette queries each selector within `view.el` and replaces the configured string with the resulting collection. With the default DOM API, `view.getUI('save')` and `view.ui.save` are native `NodeList` instances. Marionette rebinds those collections to replacement nodes after each render. Use `getUI(name)` after declaring a `ui` map and binding its elements when application code needs a named element. Calling it without a declared map, before binding, or after unbinding throws `MarionetteError` with code [`MN0023`](/errors/MN0023.md). Once bound, a missing key preserves the existing `undefined` result. Use the `@ui.` form in `events`, `triggers`, Behaviors, and Regions so a selector change has one source of truth. Every `@ui.` reference must contain a non-empty name for an own, declared key in the applicable `ui` map. Missing or inherited keys throw `MarionetteError` with code [`MN0018`](/errors/MN0018.md) during normalization. Selector values must be strings. An own key with `undefined` is not diagnosed as missing by core; do not rely on a particular result for that unsupported value. An explicitly declared empty selector is a known key, though the DOM API may reject it when the selector is used. ## Optional jQuery DOM Adapter Applications that explicitly configure [`@mnjs/adapters/dom/jquery`](/docs/installation.md#jquery-dom-adapter-is-optional) before constructing Views receive jQuery collections from query methods. The [application-owned `$el` setup](/docs/dom-api.md#optional-jquery-adapter) can add a wrapper on View, CollectionView, and Behavior subclasses; no base-class helper is exported. Core examples use native collections so the default package remains jQuery-free. [Canonical source](/docs/markdown/docs/dom.interactions.md) · [Source identity](/docs/manifest.json) --- Document: docs/routing.md Canonical URL: https://marionettejs.com/docs/routing/ Markdown URL: https://marionettejs.com/docs/routing.md Reading SHA-256: c174373b58f8d7a8125dd471219d93e4ee4454969cfb385fff40f61bbad4953b # Connect routing to a feature Keep the project's existing router. A route handler can call an application function that loads data and shows a View. Marionette does not export a router or require a routing adapter. ## Choose the boundary | Responsibility | Owner | | --- | --- | | Match URLs, parse parameters, update browser history | Your router | | Validate route input, load data, handle errors, cancel superseded navigation | Application code | | Display and replace the feature's View tree | A Marionette Region | | Start, stop, and destroy the feature | A Marionette Application | Use a Region directly when navigation only replaces Views. Add an Application when the feature also needs a start/stop boundary or owns other Applications. A route change does not inherently require a new Application instance. If the project has no router, first determine whether it needs URLs at all. Local selection can be ordinary application state. For URL navigation, choose a router against the required URL, history, and deployment behavior. That decision is independent of the [data, state, and DOM integrations](/docs/choosing-integrations.md). ## Load the latest page and discard stale work This example keeps one Application alive while routes replace its root View. It retains the previous page during loading and on a current request failure. A later navigation aborts the previous request. Stopping or destroying the Application also aborts pending work and removes its displayed View. Save this module as `page-navigation.js`. `loadPage(id, { signal })` is an application dependency: it returns a Promise for an object with `title` and `body` strings. The element must already exist. No data adapter is needed for these plain objects. ```javascript import { Application, View } from 'marionette'; const PageView = View.extend({ template: () => '

    ', onRender() { this.el.querySelector('h1').textContent = this.model.title; this.el.querySelector('p').textContent = this.model.body; } }); export async function createPageNavigation({ el, loadPage }) { let pending; function cancelPending() { pending?.abort(); pending = undefined; } const Pages = Application.extend({ onBeforeStop: cancelPending, onBeforeDestroy: cancelPending }); const application = new Pages({ region: { el } }); await application.start(); async function navigate(id) { if (!application.isRunning()) return false; cancelPending(); const request = new AbortController(); pending = request; try { const page = await loadPage(id, { signal: request.signal }); if (request.signal.aborted || !application.isRunning()) return false; application.showView(new PageView({ model: page })); return true; } catch (error) { if (request.signal.aborted || !application.isRunning()) return false; throw error; } finally { if (pending === request) pending = undefined; } } return { application, navigate }; } ``` `navigate()` resolves `true` after displaying the requested page and `false` when navigation was canceled or the Application was not running. A current load or render failure rejects. Catch that rejection at the route boundary and show an error appropriate to the application. Render failures do not promise that the previous View survives; Region replacement is not transactional. The check after `await` is required even when the loader accepts an `AbortSignal`: a cache or another provider may finish work after cancellation. It also prevents a stale rejection from becoming the current page's error. The identity check in `finally` keeps an older request from clearing the newer request's cancellation handle. This controller owns cancellation for page requests. It does not make every View lifecycle asynchronous. Use Application readiness hooks for work that must finish before the *feature* can start; see [Application lifecycle](/docs/application.md#application-lifecycle). Repeated in-flight `start()` or `restart()` calls share their operation Promise, so changing their options is not a substitute for navigation cancellation. ## Connect an existing router Create the feature once, then call `navigate(id)` from the router's existing matched-route handler. For an application already using `Backbone.Router`, that can look like this: Serve this application and its API over HTTPS in production; relative requests use the application origin. ```javascript import Backbone from 'backbone'; import { createPageNavigation } from './page-navigation.js'; const status = document.querySelector('#route-status'); const { application, navigate } = await createPageNavigation({ el: document.querySelector('#page'), async loadPage(id, { signal }) { const response = await fetch(`/api/pages/${encodeURIComponent(id)}`, { signal }); if (!response.ok) throw new Error(`Page request failed: ${response.status}`); return response.json(); } }); const Router = Backbone.Router.extend({ routes: { 'pages/:id': 'page' }, page(id) { status.textContent = ''; void navigate(id).catch(() => { status.textContent = 'Could not load this page. Try again.'; }); } }); const router = new Router(); Backbone.history.start(); // When the owning application leaves this feature: // await application.stop(); // When that owner permanently releases it: // await application.destroy(); ``` The page supplies `
    ` and `

    `. The server supplies the page endpoint. Register this route within the project's existing router when one is already present; start browser history once at the application entry point. Route registration and history teardown remain the router owner's responsibility. Stop the feature on routes that leave it, and restart it with `start()` before sending it more navigation requests. Using Backbone for routing alone does not require `BackboneApi`, `setDataApi`, or `setStateApi`. Configure those only when Marionette owners consume Backbone data or state. Backbone's URL matching and history behavior remain [Backbone contracts](https://backbonejs.org/#Router). ## Verify the integration Check the behavior at the route boundary: - Navigate from a slow request to a fast one. The fast page must remain visible when the slow request later resolves or rejects. - Navigate away or destroy the feature during loading. No late View may appear. - Fail the current load. Surface the error and allow a later navigation to succeed. - Replace a displayed page. Its old View must be destroyed through its Region. - Follow a direct URL and use browser back/forward. Those checks exercise the router and hosting configuration, beyond the Marionette example. The executable example fixture tests replacement, cancellation, load failure, stop/restart, and destruction using deferred loaders, including loaders that ignore abort. It does not test a particular router or server deployment. [Canonical source](/docs/markdown/docs/routing.md) · [Source identity](/docs/manifest.json) --- Document: docs/task-recipes.md Canonical URL: https://marionettejs.com/docs/task-recipes/ Markdown URL: https://marionettejs.com/docs/task-recipes.md Reading SHA-256: 89bc04b44c3d8247b325c143fe00f9ddb8d55a4738327a70a8ca7a6a3bb920f1 # Task recipes Start with the resource that must survive or be cleaned up. These recipes use Marionette ownership to keep application behavior predictable. Preserve an existing compatible integration; each task identifies when another one is needed. | Task | Start here | Owner and decision | | --- | --- | --- | | Save a draft without losing focus | [Forms](/docs/forms-and-accessibility.md) | The form View owns input DOM and its pending save; update status without rerendering. | | Change pages while requests overlap | [Routing](/docs/routing.md) | The application owns URL handling and cancellation; the Region owns the active page. | | Refresh a root class or ARIA state | [Root attributes](/docs/view.md#refreshing-root-attributes) | Call `renderAttributes()` when only declared root attributes changed. | | Keep surviving list rows editable | [Collection reconciliation](/docs/collection-view.md#managing-children) | Keep the observable collection and surviving source objects; do not rebuild the entire CollectionView on every change. | | Reuse server-provided markup | [Prerendered content](/docs/prerendered-dom.md) | Give an existing element to its View; establish child ownership explicitly. | | Observe a shared model | [DataApi](/docs/data-api.md) | Use the existing provider, or native observable data for a new application; plain objects do not emit changes. | | React to local owner state | [State](/docs/state.md) | Choose StateApi separately from DataApi; use owner cleanup for subscriptions. | | Wrap a widget that owns DOM | [The example below](#wrap-a-dom-owning-widget) | The View owns the widget handle and tears it down before DOM removal. | ## Wrap a DOM-owning widget Use this seam for a chart, editor, map, or other widget that renders inside a Marionette-owned host. The widget factory receives a DOM element and returns a synchronous `destroy()` handle. Its own library decides rendering and data updates. Do not let Marionette and the widget both own the same descendants. ```javascript import { View } from 'marionette'; export const WidgetView = View.extend({ template: () => '
    ', initialize({ createWidget }) { this.createWidget = createWidget; this.widget = null; }, onDomRefresh() { if (!this.widget) { this.widget = this.createWidget(this.el.querySelector('[data-widget-host]')); } }, releaseWidget() { const widget = this.widget; this.widget = null; widget?.destroy(); }, onDomRemove() { this.releaseWidget(); }, onBeforeDestroy() { this.releaseWidget(); } }); ``` Here is a complete factory for trying the ownership contract without installing another library. A real widget adapter supplies the same handle. ```javascript import { Region } from 'marionette'; import { WidgetView } from './widget-view.js'; const mount = document.createElement('main'); document.body.append(mount); const region = new Region({ el: mount }); region.show(new WidgetView({ createWidget(host) { const button = document.createElement('button'); button.type = 'button'; let count = 0; button.textContent = 'Count: 0'; const increment = () => { button.textContent = `Count: ${++count}`; }; button.addEventListener('click', increment); host.append(button); return { destroy() { button.removeEventListener('click', increment); button.remove(); } }; } })); // When leaving: region.destroy(); mount.remove(); ``` With default lifecycle monitoring, `dom:refresh` runs after attached rendering and attachment of rendered content. `dom:remove` runs before that content is rerendered or detached. Thus a rerender destroys the previous widget before a new host appears. Detaching destroys the widget but retains the View; showing that View again creates a fresh widget. Destruction releases any remaining handle. Keep `monitorViewEvents` enabled for this pattern and use Marionette-managed attachment. Direct `append()`/`remove()` calls outside the lifecycle do not become Marionette attachment events. If the widget must retain expensive state across navigation, persist that state outside its disposable DOM handle or deliberately choose a different attachment policy. The factory must clean up partially acquired resources if initialization throws. An asynchronous widget loader also needs a cancellation/generation check before it attaches; follow the [navigation cancellation pattern](/docs/routing.md). A View lifecycle callback does not automatically await arbitrary third-party promises. The [executable fixture](/docs/source/test/fixtures/docs-application-guides/validate.mjs) checks one widget per attachment, teardown before rerender, detach/reshow, and final destruction. See [lifecycle](/docs/lifecycle.md) for event ordering. ## Preserve an edited row during collection changes A stable model object and a stable child View are different from matching IDs in a new array. For an observable collection, perform the provider's supported incremental operations. Then verify the unaffected child View and its input node are the same objects. Avoid calling `collectionView.render()` after every provider notification: that explicitly rebuilds children. If data arrives as an immutable replacement, use a provider/reconciliation policy that defines how source identity changes are handled. Do not assume `trackBy` or ID matching preserves the existing View's `model` object under every adapter. The [integration guide](/docs/choosing-integrations.md) identifies supported contracts; [testing](/docs/testing.md) explains the input identity and stale-subscription assertions that catch this failure. [Canonical source](/docs/markdown/docs/task-recipes.md) · [Source identity](/docs/manifest.json) --- Document: docs/typescript.md Canonical URL: https://marionettejs.com/docs/typescript/ Markdown URL: https://marionettejs.com/docs/typescript.md Reading SHA-256: e473c57281ceee2796572fec6d928ae91120e61bb20479202ca298e24b396e42 # TypeScript in an application Use the declarations shipped by the installed `marionette` package. Core does not need `@types/backbone` or an additional Marionette type package. Install type packages for an optional integration only when your application imports it; see [installation](/docs/installation.md#peer-dependencies). ## Match the compiler to the runtime For a browser application whose existing bundler emits JavaScript, a minimal starting configuration is: ```json { "compilerOptions": { "target": "ES2024", "lib": ["ES2024", "DOM", "DOM.Iterable"], "module": "ESNext", "moduleResolution": "Bundler", "strict": true, "noEmit": true, "skipLibCheck": false }, "include": ["src"] } ``` Run the application's installed compiler with `npx tsc --noEmit`, then run its normal bundler. This example assumes a toolchain supporting that target; it does not supply browser polyfills. Preserve the application's existing target when it is constrained by its supported browsers. For modules executed directly by Node, use `module: "NodeNext"` and `moduleResolution: "NodeNext"`. Mark ESM using `"type": "module"` in package.json or `.mts` files. Use `.cts` for explicit CommonJS. Select resolution according to the program that loads the emitted modules, as described in the [TypeScript compiler guide](https://www.typescriptlang.org/docs/handbook/modules/guides/choosing-compiler-options). Marionette's declarations are checked with TypeScript 6 and 7 in the repository. The [installed consumer fixture](https://github.com/marionettejs/marionette/blob/b06750c507494441f0b2298766b70087e45346a2/test/fixtures/core-types/consumer.mts) covers strict ESM, CommonJS, and bundler resolution. A successful source-only compiler run is not a substitute for checking the package your application actually installs. ## Give application options a type Annotate `initialize` when using `.extend`. The constructor and `this.options` then share that application option contract. Use public methods to expose application values rather than writing ad hoc properties through a cast. ```ts import { Region, View } from 'marionette'; const MessageView = View.extend({ template: () => '

    ', initialize(options: { message: string }) { // The annotation defines required application options. void options; }, onRender() { const paragraph = this.el.querySelector('p'); if (!paragraph) throw new Error('Message template requires a paragraph'); paragraph.textContent = this.options.message; }, message(): string { return this.options.message; } }); const mount = document.createElement('main'); document.body.append(mount); const region = new Region({ el: mount }); region.show(new MessageView({ message: 'Ready' })); // On feature removal: region.destroy(); mount.remove(); ``` `new MessageView()` and `new MessageView({ message: 42 })` are compile errors. Return-type annotations are useful on application methods that reference other inferred methods. Prefer one inheritance style within a View family. `.extend` uses a callable parent by default; blindly calling inherited `.extend()` on a native JavaScript class is not equivalent to ordinary `class extends`. The [implementation notes](https://github.com/marionettejs/marionette/blob/b06750c507494441f0b2298766b70087e45346a2/docs/maintainers/types.md) document advanced constructor and mixed-inheritance boundaries for library authors. ## Narrow the DOM at its use site A selector does not prove that a template contains a particular element type. Check nullable query results. Native DOM event `target` can be a nested element; Marionette's `delegateTarget` is the matched delegated element. This complete View narrows the matched element at the event boundary: ```ts import { View } from 'marionette'; import type { DelegatedEvent } from 'marionette'; export const SearchView = View.extend({ template: () => '

    ', events: { 'input input': 'showQuery' }, showQuery(event: DelegatedEvent) { const input = event.delegateTarget; const output = this.el.querySelector('p'); if (!(input instanceof HTMLInputElement) || !output) { throw new Error('Search template is incomplete'); } output.textContent = input.value; } }); ``` The example checks the matched control rather than asserting that an arbitrary event target is an input. For elements from another window, use that element's owner-document constructors or a suitable structural check. Do not use a broad `any` cast to hide a package-version mismatch. ## Keep lifecycle result types distinct `View#destroy()` and `Region#destroy()` are synchronous. Application lifecycle operations return promises; await `app.start()`, `app.stop()`, and `app.destroy()` when later work depends on their completion. A `true` result means the requested state was reached, including an already-running `start()` or repeated `destroy()`. A superseded transition resolves `false`; starting a destroyed application also resolves `false`. Rejection reports a failed transition. See [Application](/docs/application.md) for exact states. Types do not establish data validity at a network boundary, protect against stale asynchronous results, or demonstrate focus retention. Validate external data in the application and test runtime behavior alongside the compiler. [Canonical source](/docs/markdown/docs/typescript.md) · [Source identity](/docs/manifest.json) --- Document: docs/testing.md Canonical URL: https://marionettejs.com/docs/testing/ Markdown URL: https://marionettejs.com/docs/testing.md Reading SHA-256: c27414d49c5ff018afb7dc7e0e4c748c1d8d311f04a1e4c4cba720a9503893f9 # Testing a Marionette application Test observable application behavior through the same package and integrations used in production. Keep fast View tests for local contracts, then use a real browser for focus, layout, navigation, and third-party DOM behavior. Marionette does not require a particular test runner or supply a browser environment. ## A small View test This complete example uses Node's test runner and a DOM supplied by `jsdom`. Install `jsdom` as a development dependency and run `node --test counter.test.mjs`. Keep DOM-dependent modules inside the configured environment. The View uses no Backbone or jQuery adapter. ```javascript // counter.test.mjs import assert from 'node:assert/strict'; import test from 'node:test'; import { JSDOM } from 'jsdom'; test('a delegated button updates the existing screen and stops after destruction', async () => { const dom = new JSDOM('
    '); globalThis.window = dom.window; globalThis.document = dom.window.document; let region; try { const { Region, View } = await import('marionette'); const Counter = View.extend({ template: () => '0', events: { 'click button': 'increment' }, initialize() { this.count = 0; }, increment(event) { assert.equal(event.delegateTarget.tagName, 'BUTTON'); this.count += 1; this.el.querySelector('output').textContent = String(this.count); } }); region = new Region({ el: document.querySelector('main') }); const view = new Counter(); region.show(view); const button = view.el.querySelector('button'); button.querySelector('span').click(); assert.equal(view.el.querySelector('output').textContent, '1'); assert.equal(view.el.querySelector('button'), button); region.empty(); assert.equal(view.isDestroyed(), true); button.click(); assert.equal(view.count, 1); assert.equal(document.querySelector('main').children.length, 0); } finally { region?.destroy(); dom.window.close(); delete globalThis.window; delete globalThis.document; } }); ``` Run tests that mutate global DOM objects in isolation, or use your runner's DOM environment and cleanup hooks. Configure adapters before constructing owners. Use `createMarionette()` for independent runtimes with different global defaults; it is not necessary for every test. Avoid test order dependence from shared Radio channels or runtime configuration. ## Assert resource ownership | Change under test | Assertions that establish behavior | | --- | --- | | Region replacement | The new View is current; the old one is destroyed exactly once; its subscriptions no longer fire. | | Deliberate detach | The View is alive and reusable; another owner eventually shows or destroys it. | | Collection update | Unaffected child View and input identities survive; draft, focus, and selection remain; removed children are destroyed. | | Provider/source replacement | Updates from the new source reach the owner; old source updates no longer do. | | Async navigation | Resolve the second request first; a late first success or failure cannot replace it. Test a client that ignores abort. | | Application shutdown | Await stop/destroy; pending work is canceled; no late DOM write occurs. | | Widget rendering | Acquire once per host; release before replacement and on final removal; no duplicate global listeners. | Do not prove teardown only by asserting that `destroy()` was called. Trigger the old source, click a retained detached node, or resolve the late promise and verify that nothing commits. The [routing fixture](/docs/source/test/fixtures/docs-routing/validate.mjs) and [form/widget fixture](/docs/source/test/fixtures/docs-application-guides/validate.mjs) show these assertions against the exact documented examples. ## Use a real browser where it changes the conclusion A simulated DOM can establish event wiring and object identity. It cannot prove layout, paint, native constraint-validation presentation, or announcements by assistive technology. In the browser, test keyboard submission, focus and selection through provider updates, direct navigation to a deep URL, and cleanup after leaving and returning to a feature. Exercise the actual selected DomApi and widget, not a mock that always preserves nodes. Observe failures through the rendered UI and application API boundary. A green compiler, coverage percentage, or matching screenshot alone does not establish that the intended operation succeeded. Keep test data anonymous and deterministic. ## Keep examples and evidence together For repository contributions, an `executable-example` marker connects a canonical JavaScript fence to a fixture that extracts and executes it. The marker checker checks the connection, not behavior. `npm run test:fixtures` builds and tests installed package artifacts; `npm run docs:check` verifies example markers and document links. Application projects should use their own package lock and CI commands rather than copying Marionette's maintainer workflow wholesale. [Canonical source](/docs/markdown/docs/testing.md) · [Source identity](/docs/manifest.json) --- Document: docs/forms-and-accessibility.md Canonical URL: https://marionettejs.com/docs/forms-and-accessibility/ Markdown URL: https://marionettejs.com/docs/forms-and-accessibility.md Reading SHA-256: 6befedf3629ad5bc6e1d0b571fe2fbb4b18cd70b1d43f5d66dd9898a0e9ce60c # Forms and accessible interactions Use native form controls and keep an unfinished draft in the existing input DOM. A Marionette View owns the form and its pending save; the application supplies the persistence operation. A DataApi or StateApi is not required for this local draft. Choose a shared observable source only when other owners need to observe it. ## Save without replacing the user's input This complete module uses the default DOM and event implementations. The template contains only trusted, fixed markup. User data is assigned through `value` or `textContent`. Each instance gets its own label and message IDs. ```javascript import { View } from 'marionette'; export const ProfileForm = View.extend({ tagName: 'form', attributes: { 'aria-label': 'Profile' }, templateContext() { return { id: this.cid }; }, template({ id }) { return `

    `; }, events: { submit: 'onSubmit' }, initialize({ displayName, save }) { this.initialName = displayName; this.save = save; this.pendingSave = null; }, onRender() { this.el.elements.namedItem('displayName').value = this.initialName; }, onBeforeRender() { this.cancelSave(); }, onSubmit(event) { event.preventDefault(); return this.submit(); }, async submit() { if (this.isDestroyed() || this.pendingSave) return false; if (!this.el.reportValidity()) return false; const input = this.el.elements.namedItem('displayName'); const button = this.el.querySelector('button'); const status = this.el.querySelector('[role="status"]'); const request = new AbortController(); this.pendingSave = request; input.readOnly = true; button.disabled = true; this.el.setAttribute('aria-busy', 'true'); status.textContent = 'Saving…'; const displayName = input.value; try { await this.save({ displayName }, { signal: request.signal }); if (request.signal.aborted || this.isDestroyed()) return false; this.initialName = displayName; status.textContent = 'Saved.'; return true; } catch { if (request.signal.aborted || this.isDestroyed()) return false; status.textContent = 'Could not save. Your changes are still here. Try again.'; return false; } finally { if (this.pendingSave === request) { this.pendingSave = null; input.readOnly = false; button.disabled = false; this.el.removeAttribute('aria-busy'); } } }, cancelSave() { this.pendingSave?.abort(); this.pendingSave = null; this.el.removeAttribute('aria-busy'); }, onBeforeDestroy() { this.cancelSave(); } }); ``` Mount it through a Region. This example's persistence is deliberately in memory; replace `save` with the application's API client for durable storage. ```javascript import { Region } from 'marionette'; import { ProfileForm } from './profile-form.js'; const mount = document.createElement('main'); document.body.append(mount); const region = new Region({ el: mount }); let savedProfile = { displayName: 'Taylor' }; region.show(new ProfileForm({ ...savedProfile, async save(profile, { signal }) { signal.throwIfAborted(); savedProfile = profile; } })); // When the feature is removed: region.destroy(); mount.remove(); ``` The submit event handles the button and keyboard submission. Native `required` validation prevents an empty save. While saving, the input is read-only and the button is disabled; duplicate programmatic submissions return `false`. A failure keeps the same input, its value, and its selection. The live status announces the outcome without replacing the form or forcing focus elsewhere. Do not call `render()` for a status change. An explicit rerender is a reset to the last saved value: it cancels a pending request before replacing the controls. Destruction also aborts the request. The signal check matters even if a client ignores cancellation. Aborting does **not** prove a server rolled back a write; reconcile ambiguous writes through the application's API contract. For server field validation, map known field errors to visible messages, set `aria-invalid="true"`, and connect each message with `aria-describedby`. Clear those errors when corrected. Keep an error summary focusable when the user needs to move among several invalid fields. Avoid displaying raw server errors. [WAI's form guidance](https://www.w3.org/WAI/tutorials/forms/) explains labels and structure; its [notification guidance](https://www.w3.org/WAI/tutorials/forms/notifications/) explains associating errors and communicating results. ## Focus when a screen changes A Region owns destruction and insertion; it does not decide the application's navigation focus policy. After a user-initiated route change has successfully shown the new screen, update `document.title` and focus a meaningful heading with `tabindex="-1"`. Keep that operation after the current-navigation check in the [routing guide](/docs/routing.md). A stale response must neither replace the page nor move focus. Background refreshes should normally leave focus where the user put it. Prefer `', events: { 'click .toggle': 'toggle' }, createState() { return { open: false }; }, toggle() { const state = this.getState(); state.open = !state.open; this.render(); }, onRender() { this.el.dataset.open = String(this.getState().open); } }); export const disclosure = new Disclosure().render(); ``` ## StateApi The public adapter contract is deliberately small: ```javascript StateApi.subscribe(source, eventName, callback, context); // returns a cleanup function StateApi.disposeOwned?.(source); ``` `subscribe` registers handlers for future events. It receives each `stateEvents` name unchanged and calls the provided callback with the source's native payload. Every call must return an idempotent cleanup function. Marionette retains it outside the owner's public event registry and invokes it during destruction. Therefore calling `owner.off()` cannot disable state-source cleanup. Subscription setup errors propagate to the caller; event-map registration is not rolled back. `disposeOwned` is called only for a `createState()` result, after subscriptions are released. It is never called for a supplied or declared `state` source. The default StateApi does not pretend a plain object is observable. Declaring `stateEvents` for a source it cannot observe throws `MN0037`. Configure StateApi on the default runtime before constructing its consumers: ```javascript import { setStateApi } from 'marionette'; setStateApi({ subscribe(source, eventName, callback, context) { return source.subscribe(eventName, (...args) => callback.apply(context, args)); }, disposeOwned(source) { source.dispose(); } }); ``` `Application.setStateApi()`, `MnObject.setStateApi()`, `View.setStateApi()`, `CollectionView.setStateApi()`, and `Behavior.setStateApi()` configure a class or subclass independently. Repeated configuration overlays only that receiving class; it does not mutate its parent or sibling classes. StateApi selection is independent of DataApi selection, though one object may implement both. ## stateEvents `stateEvents` retains Marionette's declarative event-map shape. Handler names are resolved on the owner, while event vocabulary and callback arguments belong to the selected adapter. ```javascript import { View } from 'marionette'; // Fragment: provide an actor source and its matching StateApi at construction. const ActorView = View.extend({ stateEvents: { 'actor.transition': 'onTransition' }, onTransition(snapshot) { this.el.dataset.phase = snapshot.value; } }); ``` Changing from one state provider to another may require changing event names. Marionette does not add universal `get`, `set`, `reset`, `dispatch`, or `send` methods to state owners. ## Application lifetime ```javascript import { Application } from 'marionette'; const Session = Application.extend({ createState() { return { phase: 'stopped' }; }, onStart() { this.getState().phase = 'ready'; }, onStop() { this.getState().phase = 'stopped'; } }); export const session = new Session(); export const sessionState = session.getState(); export const started = await session.start(); export const stopped = await session.stop(); export const restarted = await session.restart(); ``` Application readiness remains the only asynchronous lifecycle boundary. Code that mutates a state source after awaited work must still check the readiness `AbortSignal` before committing stale results. ## Behavior lifetime ```javascript import { Behavior, View } from 'marionette'; const Disclosure = Behavior.extend({ events: { 'click .disclosure': 'toggleDisclosure' }, createState() { return { open: false }; }, toggleDisclosure() { const state = this.getState(); state.open = !state.open; this.view.render(); }, onRender() { this.view.el.dataset.disclosureOpen = String(this.getState().open); } }); const Settings = View.extend({ el() { return document.querySelector('#settings'); }, behaviors: [Disclosure], events: { 'click .selection': 'toggleSelection' }, template: () => '', createState() { return { selected: false }; }, toggleSelection() { const state = this.getState(); state.selected = !state.selected; this.render(); }, onRender() { this.el.dataset.selected = String(this.getState().selected); } }); export const settings = new Settings().render(); ``` A Behavior that receives its View's source through `state` borrows it. A Behavior-private `createState()` result is owned only by that Behavior. ## Migration from the v5 alpha State The experimental concrete `Marionette.State` export was removed from core. For non-observable local values, return a plain object from `createState()` and use property access. For reactive values, supply the provider's real source and a matching StateApi. Do not alias the removed State to another model type. ```javascript // Before const state = owner.getState(); state.set('open', true); ``` ```javascript // Plain-object source const state = owner.getState(); state.open = true; ``` [Canonical source](/docs/markdown/docs/marionette.state.md) · [Source identity](/docs/manifest.json) --- Document: docs/data.api.md Canonical URL: https://marionettejs.com/docs/data-api/ Markdown URL: https://marionettejs.com/docs/data-api.md Reading SHA-256: 1c38638bd95125841e3567665898932994feba558e097e09d0e5a567fd034378 # Data API Display plain objects and arrays directly, or connect your data library through `DataApi`. The adapter tells Marionette how to read models, obtain collection order, and observe changes. Core does not require Backbone-shaped `cid`, `attributes`, `get`, `models`, or collection event payloads. The default adapter treats models as plain objects and collections as ordered arrays. Plain arrays are static snapshots: mutating one does not notify Marionette. Call `render()` after changing a plain array. Declaring `modelEvents` or `collectionEvents` for an unobservable plain value throws `MN0037` instead of manufacturing an event system. Both Backbone models and collections (through `BackboneApi`) and `@mnjs/data` models and collections are observable alternatives; preserve an existing provider that meets the task. ```javascript import { CollectionView, View } from 'marionette'; const ChildView = View.extend({ tagName: 'li', template: model => model.name }); const ListView = CollectionView.extend({ childView: ChildView }); const models = [{ name: 'one' }, { name: 'two' }]; const list = new ListView({ collection: models }); list.render(); ``` ## Adapter contract An adapter supplies seven methods: | Method | Purpose | | --- | --- | | `key(model)` | Return a stable `Map` key used to associate a model with its child View. | | `get(model, attribute)` | Read one named value for string comparators and filters. | | `has(model, attribute)` | Distinguish a missing value from a present value of `undefined`. | | `serialize(model)` | Return the data passed to a template. | | `models(collection)` | Return the collection's current ordered model snapshot. | | `subscribe(entity, eventName, callback, context)` | Subscribe to an application entity event and return an idempotent cleanup function. | | `observeCollection(collection, callback, context)` | Observe structural collection changes and return an idempotent cleanup function. | `key()` must remain stable while a model belongs to a CollectionView and must be unique among the models currently owned by that CollectionView. The default adapter uses object identity. Adapters for immutable sources may use a stable source identity instead. `models()` must return an ordered model snapshot after the source mutation is complete. Marionette does not mutate that array. `subscribe()` registers handlers for future events and preserves the source event's arguments. It must return an idempotent cleanup function. Marionette invokes that function during explicit undelegation or owner destruction. Subscription setup errors propagate to the caller; event-map registration is not rolled back. `observeCollection()` also returns an idempotent cleanup function. Adapters are responsible for fulfilling these contracts; core does not wrap or validate each returned cleanup. `model` and `collection` are opaque adapter references. Only `null` and `undefined` mean no source; values such as `0`, `false`, and `''` can identify a source when the configured adapter supports them. Prefer a stable reference whose `get` and `serialize` methods read current values. Item changes can then notify existing Views through `subscribe` without replacing their identity. ## Collection observations `observeCollection()` reports one of three normalized records: ```javascript { kind: 'reorder' } { kind: 'reset' } { kind: 'update', added: [], removed: [], updated: [ { previous: previousModel, current: currentModel } ] } ``` `reorder` means model order changed without membership changing. `reset` means Marionette must rebuild every child. `update` supplies exact added and removed model instances. Each `updated` entry contains the previous and current model for one stable key. For an in-place update, `previous === current`. For an immutable same-key replacement, they are different objects. This distinction lets core distinguish a safe in-place render from an identity replacement. Marionette destroys and recreates the child View for an immutable same-key replacement so constructor options, `initialize`, Behaviors, entity events, and other model-dependent state all belong to the current object. Marionette constructs every same-key replacement View before removing any existing child. A replacement-construction or rendering failure propagates to the caller. Core does not undo a partial update or promise recovery on the next notification. See [synchronous failures](/docs/lifecycle.md#synchronous-failures). An in-place `updated` entry requests a child render. Adapters for mutable models with their own change events can leave `updated` empty and let child `modelEvents` handle rendering. The Backbone adapter follows this approach: merges still update collection order and filtering, without rendering children again after their model events have run. If a child was removed, detached, or destroyed while its model remained in the source, updates for that model do not recreate its View. Other children continue to update. Rendering the CollectionView again or a source reset recreates children from the current source. An immutable same-key replacement belongs only in `updated`, not in `removed` and `added`. Replacing a model with one that has a different stable key is a removal plus an addition; changing the key of a retained model is invalid. The post-mutation `models()` snapshot is authoritative and must agree with the record. Missing, duplicate, or unstable snapshot keys throw `MN0039`. Adapters must supply correct change records; core uses those records directly instead of recalculating the change to validate them. Added children follow the current snapshot order; removed children follow the previous snapshot order, regardless of their order in the change record. Observers may notify synchronously from CollectionView lifecycle hooks. Core captures each source snapshot and drains nested notifications in order, so each queued update uses the source state that accompanied it. All three record types enter one CollectionView reconciliation path. Additions create only their child Views; removals destroy only theirs; reorder moves survivor elements without rerendering them; and reset is the explicitly destructive whole-list operation. Presentation comparators may sort the child Views independently of the source's canonical order. ## Configuring an adapter Configure the application before constructing Views. In this configuration fragment, `MyDataApi` is the adapter your application supplies: ```javascript import { setDataApi } from 'marionette'; setDataApi(MyDataApi); ``` `setDataApi()` overlays the supplied own enumerable methods onto both `View` and `CollectionView`. `View.setDataApi()` and `CollectionView.setDataApi()` can configure a subclass independently. A CollectionView and its child View class must use compatible adapters. Behaviors use their owning View's adapter. Views and Behaviors work with the original model or collection, and event callbacks receive the source's native arguments. DataApi does not wrap application sources. Templates receive the data prepared by `serializeModel()` or `serializeCollection()`; see [Rendering](/docs/rendering.md). DataApi and [StateApi](/docs/state.md#stateapi) are selected independently. One adapter object may implement both contracts, but configuring one role never selects the other. ## XState actors `@mnjs/adapters/xstate` supports a parent XState v5 actor whose selected ordered collection contains stable child actor references. The adapter uses the actor reference itself as `DataApi.key()`, reads and serializes the child actor's current `snapshot.context`, and observes the parent through its snapshot subscription. A stopped and respawned actor is therefore a new model identity, even if it uses the same actor `id`. The following configuration fragment assumes `parentActor` is an already-created actor whose `context.children` contains stable child actor references. The application owns actor creation, startup, and eventual shutdown. ```javascript import createXStateActorApi from '@mnjs/adapters/xstate'; import { CollectionView, View } from 'marionette'; const XStateActorApi = createXStateActorApi({ select: snapshot => snapshot.context.children, snapshotEvent: 'actor:snapshot' }); const ChildView = View.extend({ template: context => context.label, modelEvents: { 'actor:snapshot': 'render', announced: 'onAnnounced' }, onAnnounced(event) { console.log(event.label); } }); const ListView = CollectionView.extend({ childView: ChildView }); ChildView.setDataApi(XStateActorApi); ListView.setDataApi(XStateActorApi); const view = new ListView({ collection: parentActor }).render(); ``` `snapshotEvent` is optional and has no implicit default. When configured, that exact event-map name observes `actor.subscribe()` snapshots. Every other name is passed unchanged to `actor.on()` and observes an explicitly emitted event; events sent to the actor are not surfaced automatically. The selected snapshot array should retain its reference for unrelated parent transitions. A newly subscribed observer does not receive an already-started actor's current snapshot, so initial template data comes from `getSnapshot()`. `select` is required when the result configures a CollectionView. Omit it when only actor model reads, `modelEvents`, or `stateEvents` are needed; that result does not define the collection-only `models()` and `observeCollection()` methods. Set the same adapter on `StateApi` when `stateEvents` should use this event vocabulary. Supplied actors are borrowed and never stopped by Marionette. An actor returned from `createState()` is owned and is stopped only after its Marionette-managed subscriptions are released. The adapter never traverses or stops child actors. ## Optional `@mnjs/data` sources Install `@mnjs/data` with `marionette` when an application wants a small first-party observable Model and ordered Collection without Backbone: ```sh npm install marionette@5.0.0-beta.1 @mnjs/data@5.0.0-beta.1 ``` ```javascript import { CollectionView, setDataApi, setStateApi, View } from 'marionette'; import { Collection, DataApi, Model, StateApi } from '@mnjs/data'; setDataApi(DataApi); setStateApi(StateApi); const RowView = View.extend({ tagName: 'li', template: () => '', modelEvents: { change: 'render' }, onRender() { this.el.textContent = this.model.get('label'); } }); const state = new Model({ selectedId: null }); const collection = new Collection([{ id: 1, label: 'one' }]); const list = new CollectionView({ tagName: 'ul', childView: RowView, collection, state }).render(); // Mount list.el in the application's chosen container. collection.get(1).set('label', 'updated'); // The existing row now shows "updated". ``` Unless `{ silent: true }` is passed, the package Collection emits synchronous `update`, `sort`, and `reset` events. The adapter translates them directly to normalized records. There is no separate observer queue, coalescing, or replay. Finish one structural mutation before starting another; schedule mutations from collection listeners or child lifecycle handlers after the current notification returns. Listener errors propagate and abort delivery. `move(modelOrId, index)` supports explicit list ordering without remove/add notifications or child View recreation. It and `sort` emit `sort`. Ordinary attribute changes use `model.set()` and child `modelEvents` bindings. The native adapter keys models by stable `cid`, so changing an application id does not replace its child View. Collection lookup uses current ids. Reset rejects duplicate instances and ids before changing membership; applications should keep ids unique when changing them. Lookup precedence is exact member instance, application id, then cid, regardless of collection order. Supplied native Model instances retain their identity even when the Collection configures a different model constructor; only raw attributes use that constructor. Bulk removal resolves all identities against one current snapshot, including ids changed with `{ silent: true }`. `Model.destroy()` and `Collection.destroy()` always emit their `destroy` lifecycle events, including with `{ silent: true }`. A destroyed model removes itself from each containing Collection through ordinary event subscriptions. Destroying a Collection releases its subscriptions without destroying its models. Use `Model.toObject()` for a shallow attribute copy and `Collection.toArray()` for an array of plain attribute objects. Template serialization reads attributes independently. The native package does not implement `toJSON`; pass these plain values to `JSON.stringify` explicitly. Define Model subclass `defaults` on the prototype with `Model.extend`, a prototype method, or a prototype getter; a native class field initializes too late to seed the base constructor. The package does not provide persistence, REST synchronization, validation, or implicit Backbone behavior. Native Model writes use `Object.is` equality and report sparse `changed` and `previous` maps on their event options. Nested writes are independent synchronous changes; use `options.changed` for the event being handled, since `model.changed` may already describe a nested write. `has` tests own-property presence, including undefined values. Native collection sorting is explicit and `reset` rebuilds children; there is no automatic merge/reconcile operation. See the package's [mutation semantics](/docs/data-package.md#mutation-semantics) for details. Applications using Backbone should import the bundled integration instead of configuring these methods individually. See [Optional Backbone](/docs/backbone.md). [Canonical source](/docs/markdown/docs/data.api.md) · [Source identity](/docs/manifest.json) --- Document: docs/dom.api.md Canonical URL: https://marionettejs.com/docs/dom-api/ Markdown URL: https://marionettejs.com/docs/dom-api.md Reading SHA-256: dea982ba190a485d792abec23e715bacab1a0bdd7dc1789dbff14785557c9709 # The DOM API Marionette uses a small DOM adapter for element creation, selection, attributes, content, and attachment operations. The default `DomApi` uses native browser APIs and does not require Backbone or jQuery. `View`, `CollectionView`, and `Region` expose their adapter as `Dom`. A custom adapter can replace only the operations an application needs; all omitted methods continue to use the inherited adapter. A renderer evaluates templates; `Dom.setContents` applies their output. The optional [Morphdom and Lit HTML DOM adapters](/docs/rendering.md#rendering-to-dom) preserve the selected DomApi; installing one does not select a data or state adapter. ## Element and selector boundaries `View` and `CollectionView` own a concrete DOM element. Their `el` option must be a DOM element. Resolve a selector at the call site when a View should reuse existing markup: ```javascript import { View } from 'marionette'; const view = new View({ el: document.querySelector('#content') }); ``` `Region` retains selector resolution because a Region locates its managed element relative to its `parentEl` or the document. `View#$()` and Region selector lookup both delegate to `DomApi.findEl`. With the native adapter, `View#$()` returns a `NodeList`. `Region#getEl` selects the first result and returns that native DOM element. This Region return contract does not change when `findEl` is supplied by the optional jQuery adapter. The v4 `DomApi#getEl` method is removed. DOM adapter overrides should implement `findEl(context, selector)` with an array-like result. Region `getEl` overrides are a separate extension point and must return one native DOM element. ## Native API methods The exported `DomApi` contains the following methods. This list is checked against the shipped package in CI. ### `createElement(tagName)` Creates and returns a DOM element with `document.createElement(tagName)`. Marionette uses it when a View does not receive an `el`. ### `createBuffer()` Creates and returns a `DocumentFragment` for collecting DOM nodes before one append operation. ### `getDocumentEl(el)` Returns `el.ownerDocument.documentElement`. Marionette uses that document root when determining whether a View is attached. Elements inside template content may have an owner document without a document element; Marionette treats that missing root as detached. ### `findEl(el, selector)` Finds descendants of `el` matching `selector`. The native adapter returns the `NodeList` produced by `el.querySelectorAll(selector)`. ### `hasEl(el, childEl)` Reports whether `childEl` is attached beneath `el`. Marionette uses this for attachment-state checks. ### `detachEl(el)` Removes `el` from its parent when it has one. Native listeners attached to the element remain on the detached element. ### `replaceEl(newEl, oldEl)` Replaces `oldEl` with `newEl` when `oldEl` has a parent. Passing the same element twice or an unattached `oldEl` is a no-op. ### `moveEl(el, parent, before)` Moves `el` within `parent` before the optional reference node. The native adapter uses `moveBefore` for already-attached children when available so CollectionView reordering and swapping preserve focus, selection, media, and custom-element connection state. It falls back to `insertBefore` for initial attachment and older DOM implementations; the CollectionView render pass restores focused text selection after that fallback, while older platforms may still run custom-element connection callbacks for the move. `swapChildViews()` does not restore focus or selection when it uses the `insertBefore` fallback without a child-render pass. ### `setContents(el, html)` Replaces the contents of `el` by assigning `html` to `el.innerHTML`. `null` and `undefined` produce empty contents. ### `setAttributes(el, attrs)` Applies own enumerable string keys from `attrs` as DOM attributes using `setAttribute`. Use attribute names such as `class` and `for`. View-level `className` is converted to `class` before this method is called. An explicit `null` removes an attribute. An `undefined` value or omitted key leaves the existing attribute untouched. Other values use the browser's string conversion, including `false`, `0`, and an empty string. For boolean HTML attributes, use `disabled: isDisabled ? '' : null`: the string `"false"` still means the attribute is present. ARIA and data attributes can use `false` to set `"false"`. This method does not assign JavaScript properties. Set live form values or custom element properties explicitly on the element; `value` and `checked` attributes describe input defaults. Attribute changes still have the browser's normal effects on reflected properties. When `View` or `CollectionView` creates an element, `id` and `className` declarations override matching entries in `attributes`. [`View#renderAttributes()`](/docs/view.md#refreshing-root-attributes) applies the current declarations to an existing element without tracking prior keys. Custom DomApi adapters must preserve explicit-null removal and leave undefined and omitted entries untouched. ### `appendContents(el, contents)` Appends the DOM node or `DocumentFragment` in `contents` to `el`. ### `hasContents(el)` Returns whether `el` exists and has child nodes. ### `detachContents(el)` Removes all children by assigning an empty string to `el.textContent`. This is the fast, jQuery-free default. ### `notifyAttach(el)` Notify the adapter that its element's contents are active. Called through View attachment monitoring and when construction adopts an attached root. The native implementation does nothing; Lit reconnects its directives. ### `notifyDetach(el)` Notify the adapter that its element's contents are inactive. Called through View detachment monitoring. This notification does not remove or empty the element. The native implementation does nothing; Lit disconnects its directives while retaining its rendered contents. These hooks receive only the element. They follow the existing attachment monitoring opt-out: with `monitorViewEvents: false` or monitoring handlers removed, applications must deliver the notifications they need themselves. This includes destruction: `destroy()` still removes the View and its owned resources, but does not separately disconnect adapter-managed contents when attachment monitoring is disabled. An application rendering Lit into an attached root with monitoring disabled must notify `notifyDetach(el)` when releasing that root. `detachContents(el)` remains the operation for physically emptying an element. ## Using the default API The native adapter is exported for direct use and for restoring native methods inside a customized class: ```javascript import { DomApi, View } from 'marionette'; const NativeView = View.extend(); NativeView.setDomApi(DomApi); ``` ## Providing a custom API The root `setDomApi` function overlays methods for `View`, `CollectionView`, and `Region`: ```javascript import { setDomApi } from 'marionette'; import MyDomApi from './my-dom-api.js'; setDomApi(MyDomApi); ``` Use a class setter when only one class or subclass needs the override. The setter creates a shallow adapter overlay for that class, so a partial override retains every other currently configured method. The current adapter and supplied overlay contribute own enumerable string and symbol properties. Inherited and non-enumerable properties are ignored. ```javascript import { View } from 'marionette'; export const PlainTextView = View.extend({ template() { return 'Literal markup'; } }); PlainTextView.setDomApi({ setContents(el, html) { el.textContent = html; } }); export function renderPlainText() { const view = new PlainTextView(); view.render(); return view; } ``` `PlainTextView` uses the custom `setContents`, while `View` and unrelated View subclasses retain their existing adapters. `CollectionView`, `Region`, and `View` each support this class-level pattern. ## Optional jQuery adapter Applications that rely on jQuery DOM bookkeeping can install jQuery and opt in at application boot: ```javascript import { setDomApi } from 'marionette'; import JQueryDomApi from '@mnjs/adapters/dom/jquery'; setDomApi(JQueryDomApi); ``` The optional adapter overrides `findEl`, `detachEl`, `setContents`, `appendContents`, and `detachContents`. `View#$()` consequently returns a jQuery collection. If application code also needs `$el`, initialize it once: ```javascript import $ from 'jquery'; import { View } from 'marionette'; const JQueryView = View.extend({ initialize() { this.$el = $(this.el); } }); ``` The root is fixed at construction, so the wrapper remains valid through rendering and detach/reattach. CollectionViews and Behaviors can initialize `$el` the same way. `$el` is application-owned; the adapter has no wrapper or View setup API. The native adapter does not create `$el`. The jQuery adapter does not replace Marionette's event delegator, restore Backbone.View inheritance, or allow selector strings as a View `el`. Configure those concerns separately when an application actually requires them. Prefer the native adapter for new applications. Use `@mnjs/adapters/dom/jquery` only for an existing integration that depends on jQuery selection, content, or detach semantics. [Canonical source](/docs/markdown/docs/dom.api.md) · [Source identity](/docs/manifest.json) --- Document: docs/dom.prerendered.md Canonical URL: https://marionettejs.com/docs/prerendered-dom/ Markdown URL: https://marionettejs.com/docs/prerendered-dom.md Reading SHA-256: ebfe3cf3e97c1abb6295c03ad8734f9eba845c026e6fed9a548a64a42c34c2fd # Prerendered Content View classes can be initialized with pre-rendered DOM. This can be HTML that's currently in the DOM: ```javascript import { View } from 'marionette'; const myView = new View({ el: document.querySelector('#foo-selector') }); myView.isRendered(); // true if '#foo-selector' exists and has content myView.isAttached(); // true if '#foo-selector' is in the DOM ``` Or it can be DOM created in memory: ```javascript import { View } from 'marionette'; const inMemoryHtml = document.createElement('div'); inMemoryHtml.textContent = 'Hello World!'; const myView = new View({ el: inMemoryHtml }); ``` In both of the cases at instantiation the view will determine its state as to whether the el is rendered or attached. **Note** `render` and `attach` events will not fire for the initial state as the state is set already at instantiation and is not changing. ## Managing `View` children With `View`, the `render` event is usually the best place to show child views for efficient nested rendering. However with pre-rendered DOM you may need to show child views in `initialize` as the view will already be rendered. ```javascript import { View } from 'marionette'; import HeaderView from './header-view'; const MyBaseLayout = View.extend({ regions: { header: '#header-region', content: '#content-region' }, el() { return document.querySelector('#base-layout'); }, initialize() { this.showChildView('header', new HeaderView()); } }); ``` ### Managing a Preexisting View Tree It may be the case that you need child views of already existing DOM as well. Query the existing DOM for each child's element. A Region declared with a selector may still hold that selector in `region.el` before its first show; `getRegion()` does not resolve it. Query from the owning View's concrete `el`: The page contains this existing markup before the module runs: ```html

    Existing account

    ``` ```javascript import { View } from 'marionette'; export const HeaderView = View.extend({ tagName: 'header', template: () => '

    Account

    ' }); export const BaseLayout = View.extend({ regions: { header: '#header-region', content: '#content-region' }, el() { return document.querySelector('#base-layout'); }, initialize() { this.showChildView('header', new HeaderView({ el: this.el.querySelector('#header-region').firstElementChild })); } }); export const layout = new BaseLayout(); ``` The child owns the existing `header` element. Its existing content is retained when shown because it is already rendered. Destroying the layout destroys its child and removes the owned tree. The [fixture](/docs/source/test/fixtures/docs-prerendered-content/validate.mjs) checks element identity, retained content, parent ownership, and cleanup. The same can be done with `CollectionView`. This fragment assumes an existing `#base-table` with a `tbody` containing one row per item, in source order. Supply the application's `someCollection` and configure its DataApi before construction when using an observable collection: ```javascript import { CollectionView } from 'marionette'; import RowView from './row-view'; const MyList = CollectionView.extend({ el() { return document.querySelector('#base-table'); }, childView: RowView, childViewContainer: 'tbody', buildChildView(model, ChildView, childViewOptions) { const index = this.Data.models(this.collection).indexOf(model); const childEl = this.el.querySelector('tbody').children[index]; return new ChildView({ model, ...childViewOptions, el: childEl }); } }); const myList = new MyList({ collection: someCollection }); // Unlike `View`, `CollectionView` should be rendered to build the `children` myList.render(); ``` ## Re-rendering children of a view with preexisting DOM You may be instantiating a `View` with existing HTML, but if you re-render the view, like any other view, your view will render the `template` into the view's `el` and any children will need to be re-shown. So your view will need to be prepared to handle both scenarios. ```javascript import { View } from 'marionette'; import HeaderView from './header-view'; const MyBaseLayout = View.extend({ regions: { header: '#header-region', content: '#content-region' }, el() { return document.querySelector('#base-layout'); }, initialize() { this.showChildView('header', new HeaderView({ el: this.el.querySelector('#header-region').firstElementChild })); }, template: () => '
    ', onRender() { this.showChildView('header', new HeaderView()); } }); ``` [Canonical source](/docs/markdown/docs/dom.prerendered.md) · [Source identity](/docs/manifest.json) --- Document: docs/optional-backbone.md Canonical URL: https://marionettejs.com/docs/backbone/ Markdown URL: https://marionettejs.com/docs/backbone.md Reading SHA-256: f97ac7f920d23916d365f3ff1dac27c3cbcb45668fdd020af13cddcb1dc81b83 # Optional Backbone Use Backbone models and collections with Marionette by installing the separate adapters package and selecting its Backbone integration. Marionette core does not import Backbone. Backbone models and collections are observable sources; “optional” means Marionette does not require that provider. Plain objects and arrays use the default [Data API](/docs/data-api.md) as static data. ```sh npm install @mnjs/adapters@5.0.0-beta.1 backbone ``` ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import { setDataApi } from 'marionette'; setDataApi(BackboneApi); ``` If a Marionette owner also uses a Backbone source for `state` or `createState()`, select the StateApi role separately: ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import { setStateApi } from 'marionette'; setStateApi(BackboneApi); ``` Configure `BackboneApi` once at application boot before constructing Marionette consumers or registering their subscriptions. Existing Backbone sources can be passed in; the adapter does not alter their construction or native events. For an isolated runtime, call that runtime's `setDataApi()` and `setStateApi()` methods instead of the root setters. ## What the integration does The integration supplies one combined adapter object for two related contracts: 1. As a DataApi adapter, it translates Backbone data and structural collection events. 2. As a StateApi adapter, it subscribes to Backbone state events while leaving owned Backbone state caller-controlled. The data adapter maps: | Marionette operation | Backbone source | | --- | --- | | model identity | `model.cid` | | named value read | `model.get(attribute)` | | value presence and serialization | `model.attributes` | | ordered model snapshot | `collection.models` | | application entity events | `entity.on(...)` and `entity.off(...)` | | structural observations | `sort`, `reset`, and `update` collection events | Backbone's `sort`, `reset`, and `update` payloads are translated to the neutral records documented by [`DataApi.observeCollection()`](/docs/data-api.md#collection-observations). Those Backbone-specific shapes do not enter Marionette core. As in Marionette v4, child `modelEvents` control rendering after model changes. For example, `modelEvents: { change: 'render' }` renders a child when its model changes. Collection merges still sort and filter children, but do not request another render. Backbone also reports unchanged models as merged, so treating every merge as a render request would redraw unchanged children. Sort handling follows Marionette v4: the adapter skips `sort` events carrying `add`, `remove`, or `merge` flags and handles those mutations through `update`. Explicit `collection.sort()` calls still notify the View. The observer does not retain or scan a separate membership snapshot to distinguish these events. This retains a v4 limitation: without a comparator, `collection.set()` that only reorders existing model instances emits a flagged `sort` but no `update`, so it does not automatically reorder the displayed children. Call the CollectionView's `render()` to refresh them after that operation. The original Backbone model or collection remains the value stored on a View and passed to callbacks. The integration does not wrap entities or allocate a second model graph. ## Native event identity and load order The integration uses Backbone's native `on()`, `off()`, `listenTo()`, and `stopListening()` behavior. It does not modify the Backbone namespace, constructors, prototypes, or event stores, and it does not add `triggerMethod`. Listeners registered before adapter configuration continue to work afterward: ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { setDataApi } from 'marionette'; const model = new Backbone.Model(); const onChange = () => console.log('Model changed'); model.on('change', onChange); setDataApi(BackboneApi); model.set('ready', true); // onChange still runs ``` Destroying a Marionette owner unsubscribes its adapter-managed event handlers. The adapter leaves an owned Backbone state source and its caller-owned listeners intact because Backbone has no source-wide disposal operation that can preserve them. It does not call `stopListening()`, `off()`, or persistence-capable `Backbone.Model#destroy()` on that source. ## Applications without Backbone Do not install or import Backbone solely for Marionette. Plain models and arrays work with the default DataApi: ```javascript const model = { name: 'one' }; const collection = [model, { name: 'two' }]; ``` For observable data, use [Choosing integrations](/docs/choosing-integrations.md) to select an existing integration first. If the application requires a custom integration, implement the [DataApi contract](/docs/data-api.md) rather than manufacturing Backbone-shaped `cid`, `attributes`, `models`, or event payloads. [Canonical source](/docs/markdown/docs/optional-backbone.md) · [Source identity](/docs/manifest.json) --- Document: docs/runtime-isolation.md Canonical URL: https://marionettejs.com/docs/runtime-isolation/ Markdown URL: https://marionettejs.com/docs/runtime-isolation.md Reading SHA-256: 6634e384f01d333f27f08e0b4e9829b83eeeea3f9218806d0a2f055e8ec97582 # Runtime isolation Use named imports from `marionette` when the application shares one configuration. These exports belong to the default runtime: ```javascript import { View, Radio, setRenderer } from 'marionette'; ``` `createMarionette()` creates an isolated runtime for applications that need more than one Marionette configuration in the same JavaScript process. This configuration fragment assumes the application supplies the two renderers and templates: ```javascript import { createMarionette } from 'marionette'; const admin = createMarionette(); const storefront = createMarionette(); admin.setRenderer(adminRenderer); storefront.setRenderer(storefrontRenderer); const AdminView = admin.View.extend({ template: adminTemplate }); const StorefrontView = storefront.View.extend({ template: storefrontTemplate }); ``` Each call returns its own `Application`, `Behavior`, `CollectionView`, `MnObject`, `Region`, and `View` classes. It also owns independent `DataApi`, `DomApi`, `StateApi`, EventDelegator configuration, renderer configuration, and `Radio` channel registry. Changing one runtime does not change the default runtime or another isolated runtime. New runtimes start from Marionette's built-in adapter and renderer defaults, not from later configuration applied to the default runtime. Apply shared application configuration explicitly to each runtime that needs it. Implicit composition stays inside the selected runtime. Declarative Regions, CollectionView's empty Region, and Application's root Region use the owning runtime's classes. A Region or child Application from another runtime is rejected as an ownership conflict; construct it from the receiver's runtime instead. Isolation controls implicit class composition and mutable runtime configuration. It is not a security boundary: explicitly showing a View-like object from another runtime remains allowed under the existing Region and CollectionView display contracts. The factory is optional. Calling it does not replace the default exports, and ordinary imports do not create a runtime per View or Application instance. Class-level setters remain subclass-local within either form. Configure object-style adapters against the selected runtime's setters. For example, pass the `@mnjs/adapters/dom/jquery` export to `isolated.setDomApi()`. Likewise, pass the `@mnjs/adapters/backbone` export to the isolated runtime's `setDataApi()` and `setStateApi()` methods when it consumes Backbone data or state. No implicit adapter configuration crosses runtime boundaries. ## Configuration method contract Configure a runtime or subclass before creating its instances. The setters run synchronously; they do not render Views or replace existing event subscriptions. Changing a class prototype during a live feature is not a coordinated migration of the feature's adapters or resources. | Setter | Classes configured by the root or runtime function | Update | | --- | --- | --- | | `setDataApi(api)` | `View`, `CollectionView` | Overlays own enumerable methods on each class's current DataApi. | | `setDomApi(api)` | `View`, `CollectionView`, `Region` | Overlays own enumerable methods on each class's current DomApi. | | `setStateApi(api)` | `Application`, `Behavior`, `CollectionView`, `MnObject`, `View` | Overlays own enumerable methods on each class's current StateApi. | | `setRenderer(renderer)` | `View`, `CollectionView` | Replaces template evaluation with the supplied function. | | `setEventDelegator(delegator)` | `Behavior`, `CollectionView`, `View` | Replaces the delegator with an object exposing `delegate(options)` that returns the cleanup function for that registration. | Root and runtime setter functions return `undefined`. Corresponding class methods, such as `CustomView.setDataApi(api)`, return that class and configure its prototype. Subclasses inherit configuration until they receive their own override. An existing subclass override is not overwritten by subsequently configuring its parent class. Omitting an argument is not a reset operation. In particular, object API setters retain the current overlay, while `setRenderer(undefined)` removes the configured renderer rather than restoring the default. Use a fresh `createMarionette()` when a new independent configuration should start from built-in defaults. [Canonical source](/docs/markdown/docs/runtime-isolation.md) · [Source identity](/docs/manifest.json) --- Document: packages/data/readme.md Canonical URL: https://marionettejs.com/docs/data-package/ Markdown URL: https://marionettejs.com/docs/data-package.md Reading SHA-256: 19a48f6d3c5a5ff03415389c444f98e89cef4419370de4ee04d9b4c27d89be7d # @mnjs/data Dependency-light observable `Model` and ordered `Collection` sources for Marionette v5. The package depends only on `@mnjs/utils`; models and collections can run without core or a DOM. Install `@mnjs/data` on its own for standalone use. To use it with Marionette views, install both packages and configure the runtime before creating owners: ```sh npm install marionette@5.0.0-beta.1 @mnjs/data@5.0.0-beta.1 ``` ```js import { CollectionView, View } from 'marionette'; import { Collection, DataApi } from '@mnjs/data'; const Row = View.extend({ tagName: 'li', template: () => '', modelEvents: { change: 'render' }, onRender() { this.el.querySelector('span').textContent = this.model.get('label'); } }); const List = CollectionView.extend({ tagName: 'ul', childView: Row }); Row.setDataApi(DataApi); List.setDataApi(DataApi); const collection = new Collection([{ id: 1, label: 'one' }]); const view = new List({ collection }).render(); ``` This setup selects data for the list and its child Views. State remains an independent choice. If a View also uses a `Model` as observable state, configure StateApi on that class before construction. In the example above, place this optional setup before `new List(...)`, which constructs its children when rendered: ```js import { StateApi } from '@mnjs/data'; Row.setStateApi(StateApi); ``` Supply an existing `Model` through `state`, or return an owned one from `createState()`. Declare `stateEvents` only for the changes the owner needs to observe; the model's event names and payloads remain its own contract. Use top-level setters when all affected classes intentionally share the same provider. Configure an existing isolated runtime through its corresponding setters when needed; using this package does not require creating a new runtime. `Collection` reports synchronous `kind: 'update'`, `kind: 'reorder'`, and `kind: 'reset'` records through `DataApi.observeCollection()`. `Model` and `Collection` expose `on()`, `once()`, `off()`, `trigger()`, and `triggerMethod()` for Marionette entity event maps. `DataApi.models(collection)` returns the current ordered model snapshot. `Model` provides `get`, `has`, `set`, `unset`, `clear`, `reset`, `toObject`, and `destroy`. `Collection` provides ordered `at`, `get`, `indexOf`, iteration, `forEach`, `map`, `add`, `remove`, `reset`, `move`, `sort`, `toArray`, and `destroy` operations. Pass `{ silent: true }` to a structural mutation to suppress its normalized record and entity events. `destroy()` is the exception and always emits its destruction event. Define subclass `defaults` on the prototype, for example with `Model.extend`, a prototype method, or a prototype getter. Native class fields initialize after `super()` returns, so a `defaults = { ... }` field cannot seed construction. `move(modelOrId, index)` changes list order without removing and re-adding a model. This supports drag ordering while retaining child Views and their local state. Both `move` and `sort` emit `sort`, translated to a DataApi reorder record. Update model attributes with `model.set()` and subscribe through `modelEvents` when a child should render after a change. The native DataApi uses each model's stable `cid` as its key. Application ids may change; Collection lookup reads the current ids. Duplicate instances or ids are rejected before a reset changes membership; `add` ignores an instance or id already present. Applications should keep ids unique when changing them. `get`, `remove`, and `move` resolve an exact member instance first, then an application id, then a cid. This precedence does not change when models move. Bulk removal resolves its inputs against one current membership snapshot, including silent id changes. It skips missing identities and repeated matches, returns removed Models in input order, and keeps surviving Models in collection order. If id writes temporarily create duplicates, id lookup selects the first current member; applications should restore unique ids. Supplied native Model instances retain their identity, attributes, and subclass, including when the Collection has a different `model` constructor. That constructor is used only for raw attribute objects. Initial model instances do not configure the constructor used for future raw additions. A model may belong to multiple Collections. Its `destroy` event removes it from each containing Collection, forwarding removal options such as `silent`. The destroy event itself still fires. Destroying a Collection releases subscriptions; it does not destroy its models. `model.toObject()` returns a shallow attribute copy. `collection.toArray()` returns an array of those plain objects; use `collection.models.slice()` or iteration for model instances. Template serialization reads `model.attributes` independently of these conversion methods. There is no automatic `toJSON` hook: to serialize the plain data, use `JSON.stringify(model.toObject())` or `JSON.stringify(collection.toArray())`. Collection observation uses ordinary synchronous `update`, `reset`, and `sort` events. Notifications are not combined or replayed. Complete one structural mutation before starting another: schedule mutations from collection listeners or child lifecycle handlers after the current notification returns. Errors in listeners propagate and abort delivery, as with ordinary model events. The package does not provide persistence, REST synchronization, validation, or implicit Backbone compatibility. ## Mutation semantics `set` compares values with `Object.is`: a fresh object is a change even when its contents match, while mutating a nested object in place is not observed. `has` tests own-property presence, including a present `undefined` or `null` value. Supplied attributes override defaults, including when their value is `undefined`. Model `reset` reapplies defaults and removes attributes absent from the result. Change callbacks receive `options.changed` and `options.previous`, sparse maps for that mutation. For an attribute reported in `changed`, an absent own key in `previous` means it did not exist before the mutation; an own key with value `undefined` means it existed with that value. `previous` is not a complete model snapshot. Removing an attribute reports `undefined` in `changed`; use `has` to check its current presence. Nested Model writes complete synchronously as independent changes. Use the event's `options.changed` to inspect that event: `model.changed` reflects the latest write, which may be a nested mutation by the time an outer change callback runs. Silent writes still update attributes and `changed`; no-op writes clear `changed`. Collection `add` and `remove` events originate on the Collection. Model events are forwarded by containing Collections. Sorting is explicit: a prototype comparator is used by `sort()`, but `add` and `reset` do not automatically sort. There is no `Collection.set()` merge/reconcile operation; update retained Models explicitly when refreshing a list whose child Views must retain local state. `reset` is the deliberately destructive whole-list operation for CollectionView child Views; the Collection retains supplied Model instances rather than destroying them. ## TypeScript The package includes ESM and CommonJS declarations and a TypeScript 4.6-compatible entry. `Model.extend` and `Collection.extend` retain added methods, descendants, static replacements, and their normal attribute/model constructor inference. Event registration accepts typed callbacks and maps; event names do not validate payload types. A borrowed `triggerMethod` requires a receiver with a callable `trigger` method. A custom constructor must initialize the receiver itself. An explicit object return describes a replacement instance; an unknown result stays unknown. To return the initialized receiver while preserving methods added by descendants, state that contract explicitly: ```ts import { Model } from '@mnjs/data'; const Named = Model.extend({ constructor: function( this: Receiver, attributes: { label: string } ): Receiver { Model.call(this, attributes); return this; }, label() { return String(this.get('label')); } }); ``` The same form works with `Collection`. A constructor declared to return `void` or a primitive declares ordinary construction; the caller is responsible for honoring that declaration. TypeScript's `void` return erasure can hide an object return, so the declarations cannot prove that contract from arbitrary constructor implementations. An inferred fixed receiver return does not promise methods added by later descendants. Direct native subclasses remain supported. Calling their inherited `.extend()` without an explicit constructor is rejected because that path calls the parent with `apply`, which cannot invoke a native class. An explicit constructor skips that forwarding path and owns its initialization or replacement result. TypeScript 4.6 narrows `instanceof` checks for the root constructors and ordinary method-only extensions. Its callable-intersection limitation prevents that narrowing on extensions with custom statics; directly constructed instances and those static members remain typed. Collection member types include both supplied Models and the constructor used for raw attributes. Constructor `options.model` replaces a prototype `model` factory; without either, raw attributes construct a base Model. Narrow an item with `instanceof ModelClass` before using subclass-specific methods. The instance `model` constructor has the same conservative member result type. Model attributes and `toObject()` are partial: construction, `unset`, and `clear` can leave any attribute absent. Known string keys in `set(key, value)` use the same attribute value types as object-form writes; arbitrary dynamic keys remain open. An explicitly typed Collection also checks raw attribute inputs against its model attribute shape. These are compile-time contracts, not runtime validation. [Canonical source](/docs/markdown/packages/data/readme.md) · [Source identity](/docs/manifest.json) --- Document: packages/adapters/readme.md Canonical URL: https://marionettejs.com/docs/adapters-package/ Markdown URL: https://marionettejs.com/docs/adapters-package.md Reading SHA-256: f26799985f8ac3ebab251a237ea840f876378dd0a8547667731b1948a8c5d4c5 # @mnjs/adapters First-party optional integrations for Marionette v5. The package intentionally has no root export: import only the adapter and optional peer your application uses. Installing this package does not install every provider. The adapters have separate module graphs and no import-time installation; unused integrations stay out of the application bundle. Source is grouped into `data` and `dom`, while each integration remains an explicit package subpath. ## Adapter conventions - `SomethingApi` is an object implementing an existing runtime contract. - `createSomethingApi(options)` returns that object when configuration is required. Imports do not configure Marionette. Use the existing `setDomApi`, `setDataApi`, and `setStateApi` methods before constructing instances. An integration may satisfy more than one contract: Backbone uses the same adapter object for both data and state. Setters overlay supplied methods; the last supplied version of a method wins. Configure content rendering after general DOM operations. Adapters use public APIs and document source ownership and cleanup below. Template evaluation is a function configured with `View.setRenderer()`. Projects can supply that function directly; it does not need a packaged adapter. Lit and Morphdom belong to DomApi because they apply template results to the DOM. ## Backbone ```sh npm install marionette@5.0.0-beta.1 @mnjs/adapters@5.0.0-beta.1 backbone ``` Configure DataApi before creating Views that consume Backbone models or collections. The example below covers model-backed Views. For a CollectionView, configure DataApi on both its parent CollectionView class and its child View class before construction. For a feature-specific integration, configure its View subclass: ```js import BackboneApi from '@mnjs/adapters/backbone'; import { View } from 'marionette'; const BackboneView = View.extend(); BackboneView.setDataApi(BackboneApi); ``` Use the top-level `setDataApi(BackboneApi)` when the whole application shares that data provider. Configure StateApi separately, only for owners whose state uses Backbone and needs subscriptions or owned-source cleanup: ```js BackboneView.setStateApi(BackboneApi); ``` The same adapter object can configure other state-owning classes, or the corresponding setters on an existing isolated runtime. Choosing Backbone data does not require choosing Backbone state or creating an isolated runtime. The adapter uses Backbone's native events and does not modify Backbone objects or prototypes. Releasing an owned Backbone state source removes only the adapter-managed owner subscriptions. The adapter leaves the source and its caller-owned listeners intact; it does not call source-wide `stopListening()`, `off()`, or persistence-capable `Model#destroy()` methods. ## XState actors Use the XState actor adapter when a parent actor snapshot contains stable child actor references. Actor-reference identity associates each child actor with its View; stopping and respawning an actor creates a different model identity even when the actors share an `id`. The adapter supports XState `^5.32.6`. ```sh npm install marionette@5.0.0-beta.1 @mnjs/adapters@5.0.0-beta.1 xstate ``` This configuration fragment assumes an application-owned `parentActor` whose `context.children` contains stable child actor references. Create and start the actors in the application's XState setup. ```js import createXStateActorApi from '@mnjs/adapters/xstate'; import { CollectionView, View } from 'marionette'; const XStateActorApi = createXStateActorApi({ select: snapshot => snapshot.context.children, snapshotEvent: 'actor:snapshot' }); const ActorView = View.extend({ template: context => context.label, modelEvents: { 'actor:snapshot': 'render', announced: 'onAnnounced' }, onAnnounced(event) { console.log(event.label); } }); const ActorList = CollectionView.extend({ childView: ActorView }); ActorView.setDataApi(XStateActorApi); ActorList.setDataApi(XStateActorApi); const view = new ActorList({ collection: parentActor }).render(); ``` For a CollectionView, the required selector receives the parent actor's synchronous snapshot and returns its ordered child actor references. Omit `select` when configuring only actor models or state. Templates receive each child actor's current `snapshot.context`. Configure `snapshotEvent` only when declarative `modelEvents` or `stateEvents` should observe actor snapshots; the chosen name is reserved by that adapter instance. Every other event-map name is passed to `actor.on()` and therefore observes an explicitly emitted actor event, not an event sent to the actor. Subscribing to an already-started actor does not replay its current snapshot, so initial rendering reads `getSnapshot()` directly. Replace the selected array when membership or order changes. Reusing an unchanged array lets the adapter skip comparison; a newly allocated array requires a keyed scan per observer, even if its contents are identical. Supplied parent, child, and state actors are borrowed. Destroying a Marionette owner releases its subscriptions and Views but does not stop those actors. An actor returned by an owner's `createState()` factory is owned; after releasing its subscriptions, Marionette calls this adapter's `disposeOwned()` and stops that actor. The keyed snapshot helper is private implementation only; there is no generic snapshot-source package export. ## jQuery DomApi ```sh npm install marionette@5.0.0-beta.1 @mnjs/adapters@5.0.0-beta.1 jquery ``` ```js import { View } from 'marionette'; import JQueryDomApi from '@mnjs/adapters/dom/jquery'; const JQueryView = View.extend(); JQueryView.setDomApi(JQueryDomApi); ``` If application code needs `$el`, initialize it once: ```js import $ from 'jquery'; import { View } from 'marionette'; import JQueryDomApi from '@mnjs/adapters/dom/jquery'; const JQueryView = View.extend({ initialize() { this.$el = $(this.el); } }); JQueryView.setDomApi(JQueryDomApi); ``` Views, CollectionViews, and Behaviors keep their initial root. The application owns `$el`; no wrapper helper or extra package subpath is needed. Importing an adapter subpath does not load any other adapter or optional peer. ## DOM contents The Morphdom and Lit DOM adapters update a View's contents synchronously and keep its `el` in place. Marionette still owns View events, attachment, destruction, and Regions. A parent render still destroys its Region children before updating the parent template; incremental rendering does not preserve those child Views. Keep Region placeholders empty in your templates so the adapter and Region do not both manage the same contents. Configure these adapters through `ViewClass.setDomApi(adapter)` before creating instances. The adapter overlays only its supplied methods, so unrelated DOM operations remain in place. Configure jQuery first if you need its query and attachment operations alongside Morphdom or Lit. ### Morphdom ```sh npm install marionette@5.0.0-beta.1 @mnjs/adapters@5.0.0-beta.1 morphdom ``` ```js import { View } from 'marionette'; import MorphdomDomApi from '@mnjs/adapters/dom/morphdom'; const MessageView = View.extend({ template: () => '

    Hello again.

    ' }); MessageView.setDomApi(MorphdomDomApi); ``` The template returns an HTML string containing the View's contents. Morphdom matches children using its normal rules, including element IDs. The adapter installs HTML directly into an empty root and morphs existing contents using `childrenOnly`, leaving the root's attributes under Marionette's control. Use `renderAttributes()` to refresh those attributes. ### Lit HTML ```sh npm install marionette@5.0.0-beta.1 @mnjs/adapters@5.0.0-beta.1 lit-html ``` ```js import { View } from 'marionette'; import { html } from 'lit-html'; import LitDomApi from '@mnjs/adapters/dom/lit-html'; const MessageView = View.extend({ template: ({ message }) => html`

    ${message}

    `, templateContext: { message: 'Hello again.' } }); MessageView.setDomApi(LitDomApi); ``` Configure a View subclass before creating its instances. Further subclasses inherit the adapter. Neither DOM adapter modifies View methods or needs a View reference: template evaluation stays in the renderer and the returned value goes to `Dom.setContents(el, value)`. Lit async directives can own subscriptions and other resources. Marionette calls `Dom.notifyAttach(el)` and `Dom.notifyDetach(el)` through its existing attachment monitoring. Lit translates these notifications to its directive connection API. Detaching and destroying a View disconnects its directives while preserving the View root. A View keeps its initial element for its lifetime. Destroying an already constructed View also disconnects resources created before an explicit render failed. Failed construction does not roll back initialization. Keep `monitorViewEvents` enabled on the View and its ancestors and manage attachment through Regions. If you disable monitoring or remove its handlers with `off()`, the application must call the adapter's attachment methods itself. There is no separate hidden cleanup listener. Lifecycle overrides must call parent methods, as with other Marionette lifecycle overrides. The first explicit render replaces preexisting contents; this is not hydration. Subsequent renders update Lit's marked range. A disconnected element can be adopted by another View using the same adapter without erasing its contents. Release the previous owner first; one element cannot have two active View owners. Lit event handlers use Lit's normal element receiver; use closures when a handler needs application or View state. Do not independently replace Lit's contents or switch content adapters after rendering. [Canonical source](/docs/markdown/packages/adapters/readme.md) · [Source identity](/docs/manifest.json) --- Document: docs/common.md Canonical URL: https://marionettejs.com/docs/common/ Markdown URL: https://marionettejs.com/docs/common.md Reading SHA-256: db7325305bfd423933d588166774c1307172d38f160978df9386ee4984195440 # Common Marionette Functionality Marionette classes share a small set of lifecycle, event, request, and option helpers. ## Documentation Index * [Shared helpers](#shared-helpers) * [initialize](#initialize) * [extend](#extend) * [Events API](#events-api) * [triggerMethod](#triggermethod) * [bindEvents](#bindevents) * [unbindEvents](#unbindevents) * [bindRequests](#bindrequests) * [unbindRequests](#unbindrequests) * [normalizeMethods](#normalizemethods) * [getOption](#getoption) * [mergeOptions](#mergeoptions) * [The `options` Property](#the-options-property) ## Shared helpers The reusable option, binding, and event helpers are also available from `@mnjs/utils` for components outside Marionette's classes: ```javascript import { getOption, normalizeMethods } from '@mnjs/utils'; const component = { options: { label: 'Inbox' }, getOption, normalizeMethods, onOpen() {} }; component.getOption('label'); // 'Inbox' component.normalizeMethods({ open: 'onOpen' }); ``` Install `@mnjs/utils` directly when importing it in an application. Use the same version as Marionette during prereleases. Core and native data depend on this package and use the same implementations. Helpers that read `this` can be mixed into a component or invoked with `.call(component, ...)`. ### `initialize` `initialize` is a no-op method that you can override on any Marionette class. It is called when the class is instantiated and receives the constructor arguments unchanged. The first argument is conventionally an options object. Use [`getOption`](#getoption) to read that object together with class defaults. ```javascript import { MnObject } from 'marionette'; const MyObject = MnObject.extend({ initialize(options, secondArgument) { console.log(options.foo, this.getOption('foo'), secondArgument); } }); new MyObject({ foo: 'bar' }, 'baz'); // logs "bar" "bar" "baz" ``` ### `extend` `extend` is available on Marionette class definitions for [class-based inheritance](/docs/basics.md#class-based-inheritance). ### Events API Marionette classes include Marionette's owned [Events API](/docs/events.md). Each class can emit events and listen to other objects that implement the compatible event interface, including native Backbone emitters. The separate [`Backbone integration`](/docs/events.md#backbone-interop) selects data reads and collection observation; the core Events API does not require Backbone. The Events API should not be confused with [view `events`](/docs/dom-interactions.md#view-events), which capture DOM events. ### `triggerMethod` `triggerMethod` calls a matching method and then triggers an event on the object. The first letter of each event-name segment is capitalized and `on` is prepended: * `triggerMethod('foo')` calls `onFoo` and triggers `foo`. * `triggerMethod('before:foo')` calls `onBeforeFoo` and triggers `before:foo`. Arguments after the event name are passed to both the method and event. The matching method is resolved through `getOption`, runs first with the Marionette object as its context, and supplies the return value of `triggerMethod`. If that method throws, the event is not triggered. ```javascript import { MnObject } from 'marionette'; const MyObject = MnObject.extend({ onFoo(value) { return value.toUpperCase(); } }); const object = new MyObject(); object.on('foo', value => console.log(value)); object.triggerMethod('foo', 'bar'); // logs "bar" and returns "BAR" ``` See the [Marionette events documentation](/docs/events.md#triggermethod) for the complete event and method-handler contract. ### `bindEvents` `bindEvents(entity, bindings)` uses the Marionette object's `listenTo` API to bind events from another compatible event emitter. The binding map associates event names with functions or method names on the listening object. The method returns the listening object. Marionette classes and [Radio](/docs/radio.md) channels implement the required event interface. Backbone models, collections, and other Backbone emitters can participate directly through compatible `on` and `off` methods. Configure the [`Backbone integration`](/docs/events.md#backbone-interop) separately when a View also needs Backbone data reads, serialization, or collection observation. Binding maps follow the declared object contract. An own enumerable `__proto__` event name is rejected with code `MN0026` before any listener is added. This restriction applies only to entity-event maps; Marionette's direct Events API supports `__proto__` as an ordinary event name. ### `unbindEvents` `unbindEvents(entity, bindings)` stops the subscriptions represented by a binding map. Without a binding map, it stops every subscription that this Marionette object established to that entity. It does not remove listeners owned by other objects or direct handlers registered on the entity. The method returns the listening object. When selectively unbinding with a map, an own enumerable `__proto__` event name is rejected with `MarionetteError` code `MN0026` before any listener is removed. ### `bindRequests` `bindRequests(channel, bindings)` registers replies on a [Radio](/docs/radio.md) channel. The binding map associates request names with functions or method names on the Marionette object. Reply methods run with that object as their context, and `bindRequests` returns the object. Binding maps follow the declared object contract. String-named handlers must resolve to callable methods on the receiver. ### `unbindRequests` `unbindRequests(channel, bindings)` removes the replies represented by a binding map. Without a binding map, it removes every reply owned by this object from that channel. Replies owned by other objects remain registered. The method returns the object. > **Warning:** Request bindings created manually retain their owner as reply > context. To avoid memory leaks, call `unbindRequests` in or before > `onBeforeDestroy`, and whenever a shorter binding lifetime ends. `MnObject` and `Application` instead support the declarative `channelName`, `radioEvents`, and `radioRequests` options; those owned bindings are cleaned up when the owner is destroyed. A `View` using `bindRequests` directly should call `unbindRequests` as part of its own cleanup. The following example shows both event and request bindings remaining scoped to their owner. ```javascript import { MnObject, Radio } from 'marionette'; const source = new MnObject(); const channel = Radio.channel('common-owner-bindings'); const unrelatedMessages = []; source.on('status', value => unrelatedMessages.push(value)); channel.reply('status:other', () => 'other'); const Owner = MnObject.extend({ initialize() { this.messages = []; this.bindEvents(source, { status: 'onStatus' }); this.bindRequests(channel, { 'status:current': 'getStatus' }); }, onStatus(value) { this.messages.push(value); }, getStatus() { return this.messages[this.messages.length - 1]; } }); const owner = new Owner(); source.trigger('status', 'ready'); const ownerReply = channel.request('status:current'); // "ready" owner.unbindEvents(source); owner.unbindRequests(channel); source.trigger('status', 'after'); const ownerReplyAfterCleanup = channel.request('status:current'); // undefined const unrelatedReplyAfterCleanup = channel.request('status:other'); // "other" export { Radio, owner, ownerReply, ownerReplyAfterCleanup, unrelatedMessages, unrelatedReplyAfterCleanup }; ``` ### `normalizeMethods` `normalizeMethods(bindings)` returns a fresh map with method-name strings replaced by function references from the Marionette object. Only the map's own enumerable string keys are normalized; inherited, symbol, and non-enumerable properties are ignored. A literal own `__proto__` entry remains a handler key without changing the returned object's prototype. Every supplied handler must be a function or a string that resolves to a callable own or inherited method on the binding context. Otherwise Marionette throws `MarionetteError` with code `MN0019`. This invariant also applies to event and request binding maps, including their unbind operations, and to model, collection, Radio, and child-view event bindings. ```javascript import { View } from 'marionette'; const MyView = View.extend({ initialize() { this.normalizedActions = this.normalizeMethods({ 'action:one': 'handleActionOne', 'action:two': this.handleActionTwo }); }, handleActionOne() { console.log('action:one'); }, handleActionTwo() { console.log('action:two'); } }); ``` ### `getOption` `getOption(name)` first reads the named value from the merged `options` object. If that value is `undefined`, it falls back to the same property on the instance or its prototype. Explicit option values such as `null`, `false`, `0`, and an empty string are returned without falling back. Function values are returned without being invoked. ### `mergeOptions` `mergeOptions(options, keys)` copies selected option values directly onto the class instance. `keys` must be an array when options are present. Only requested own enumerable string properties with values other than `undefined` are copied; inherited, symbol, and non-enumerable properties are ignored. ### The `options` Property A class-level `options` property supplies defaults. Marionette creates a fresh `this.options` object for each instance by merging those defaults with the constructor options; constructor values take precedence. The `options` argument received by `initialize` remains the raw object supplied by the caller, so use `getOption` when class defaults must be included. `mergeOptions` is separate: it copies only named values directly onto the instance for APIs that need instance properties. ```javascript import { MnObject } from 'marionette'; const service = { name: 'example' }; const Example = MnObject.extend({ enabled: true, options: { mode: 'default' }, initialize(options) { this.rawMode = options.mode; this.mergeOptions(options, ['service']); } }); const example = new Example({ enabled: false, service, extra: 'kept only in this.options' }); const rawMode = example.rawMode; // undefined example.getOption('mode'); // "default" example.getOption('enabled'); // false example.getOption('extra'); // "kept only in this.options" console.log(example.service === service); // true export { example, rawMode, service }; ``` ## Marionette Classes Marionette provides classes for building a view tree and application structure. [Continue Reading...](/docs/classes.md). [Canonical source](/docs/markdown/docs/common.md) · [Source identity](/docs/manifest.json) --- Document: docs/events.md Canonical URL: https://marionettejs.com/docs/events/ Markdown URL: https://marionettejs.com/docs/events.md Reading SHA-256: c3bd1948bed6caf6ac6e9a4eafa49f02072d3b9ed1980d7b23145c244faea4ac # Marionette Events Marionette provides its own `Events` primitive for communication between objects. It is exported from `marionette`, mixed into every [Marionette class](/docs/classes.md), and does not require Backbone. These object events are separate from [DOM events](/docs/dom-interactions.md#canonical-view-interaction). ## Documentation Index * [Triggering and Listening to Events](#triggering-and-listening-to-events) * [Events API](#events-api) * [`triggerMethod`](#triggermethod) * [Listening to Events](#listening-to-events) * [`onEvent` Binding](#onevent-binding) * [Backbone interop](#backbone-interop) * [Private bookkeeping](#private-bookkeeping) * [View events and triggers](#view-events-and-triggers) * [View entity events](#view-entity-events) * [Child View Events](#child-view-events) * [Event Bubbling](#event-bubbling) * [Using CollectionView](#using-collectionview) * [A Child View's Event Prefix](#a-child-views-event-prefix) * [Explicit Event Listeners](#explicit-event-listeners) * [Attaching Functions](#attaching-functions) * [Using `CollectionView`'s `childViewEvents`](#using-collectionviews-childviewevents) * [Triggering Events on Child Events](#triggering-events-on-child-events) * [Using `CollectionView`'s `childViewTriggers`](#using-collectionviews-childviewtriggers) * [Lifecycle Events](#lifecycle-events) ## Triggering and Listening to Events Use the `Events` export directly when a plain object needs Marionette's event API, or use the same methods already present on a Marionette class. ```javascript import { Events, MnObject } from 'marionette'; const emitter = Object.assign({}, Events); const listener = new MnObject(); listener.listenTo(emitter, 'status:changed', status => { console.log(status); }); emitter.trigger('status:changed', 'ready'); listener.stopListening(emitter); ``` ### Events API | Method | Purpose | | --- | --- | | `on(name, callback, context?)` | Register a callback on this object. | | `off(name?, callback?, context?)` | Remove matching callbacks registered with `on`. | | `trigger(name, ...args)` | Trigger one or more named events. | | `once(name, callback, context?)` | Register a callback that is removed after its first call. | | `listenTo(object, name, callback)` | Listen to another emitter while tracking the relationship on this object. | | `stopListening(object?, name?, callback?)` | Remove relationships created with `listenTo` or `listenToOnce`. | | `listenToOnce(object, name, callback)` | Listen to another emitter once. | | `triggerMethod(name, ...args)` | Trigger an event and call its matching `onEventName` method. | `trigger`, `on`, `off`, `once`, `listenTo`, `listenToOnce`, and `stopListening` accept space-separated event names. `triggerMethod` delegates to `trigger` for listener notification, but call it once per event when you need matching `onEventName` methods. Object-form `trigger` maps each key to the single value passed to that event's handlers: ```javascript emitter.on('start stop', value => console.log(value)); emitter.trigger('start stop', 'manual'); emitter.trigger({ start: 'automatic', stop: 'complete' }); ``` During a multi-name or mapped `trigger` call, calling `off()` from a handler removes subscriptions for subsequent calls but does not cancel the remaining event names in the current call. For example, `off()` inside a `start` handler still allows the existing `stop` handlers in `trigger('start stop')` to run. Calling `off('stop', handler)` inside `start` instead removes that handler before `stop` is dispatched. A nested `trigger` call uses the current subscriptions. `once` registers its generated callback through the object's overridable `on` method, and `listenToOnce` registers through overridable `listenTo`. This preserves the extension points used by event-lifecycle mixins. Likewise, `listenTo` and `stopListening` call an emitter's documented three-argument `on` and `off` methods exactly once per binding. ### `triggerMethod` `triggerMethod` invokes the matching `onEventName` method when it exists, then fires the named event on the instance. If there are no listeners or matching method, the call still succeeds. All arguments after the event name are passed to both the method and event handlers. ```javascript import { View } from 'marionette'; const MyView = View.extend({ callMethod(myString) { console.log(myString + ' was passed'); } }); const myView = new MyView(); myView.on('something:happened', myView.callMethod); /* Calls callMethod('foo'); */ myView.triggerMethod('something:happened', 'foo'); ``` **The `triggerMethod` method is available to [all Marionette classes](/docs/common.md#triggermethod).** ### Listening to Events Use `on` to register a callback directly on an emitter: ```javascript import { View } from 'marionette'; const MyView = View.extend({ initialize() { this.on('event:happened', this.logCall); }, logCall(myVal) { console.log(myVal); } }); ``` Use `listenTo` when the listener should own and later clean up the subscription: ```javascript import { View } from 'marionette'; const OtherView = View.extend({ initialize({ source }) { this.listenTo(source, 'event:happened', this.logCall); }, logCall(myVal) { console.log(myVal); } }); const MyView = View.extend(); const myView = new MyView(); const otherView = new OtherView({ source: myView }); myView.triggerMethod('event:happened', 'someValue'); // Logs 'someValue' ``` `listenTo` calls the callback with the listener as its context and records the relationship for `stopListening`. A direct `on` subscription must be removed with `off` when it is no longer needed. Marionette view lifecycles also clean up their tracked `listenTo` relationships during destruction. ### Backbone interop Backbone models and collections are observable event sources. Marionette `listenTo` and `stopListening` work directly with their native event interface, without changing Backbone. Select the integration separately when a View needs Backbone model reads, serialization, or structural collection observation: ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const model = new Backbone.Model(); const view = new View({ model }); view.listenTo(model, 'change', () => { // ... }); ``` The integration subscribes through Backbone's native event methods. It does not modify Backbone objects or prototypes, so existing listeners and Backbone's own listener bookkeeping remain intact. Marionette `listenTo` and `stopListening` interoperate with native Backbone objects, and Backbone can likewise listen to Marionette evented objects. ### Event names Event callbacks are dispatched only when they were explicitly registered with `on`, `once`, `listenTo`, or `listenToOnce`. Names that also exist on `Object.prototype`, including `constructor`, `toString`, and `__proto__`, are ordinary event names and do not affect the event store's prototype. Remove them through the corresponding `off` or `stopListening` API as with any other name. ### Private bookkeeping Marionette stores event internals under `_rdEvents`, `_rdListeningTo`, `_rdListeners`, and `_rdListenId`. These fields are private and replace the Backbone-shaped `_events`, `_listeningTo`, and `_listenId` names. Plugins should use `on`, `off`, `listenTo`, and `stopListening` instead of reading or writing either set of private fields. #### `onEvent` Binding In addition to triggering listeners, `triggerMethod` can call specially named methods on the instance. For example, a view that has been rendered will internally fire `view.triggerMethod('render')` and call `onRender` - providing a handy way to add behavior to your views. Determining what method an event will call is easy, we will outline this with an example using `before:dom:refresh` though this also works with any custom events you want to fire: 1. Split the words around the `:` characters - so `before`, `dom`, `refresh` 2. Capitalize the first letter of each word - `Before`, `Dom`, `Refresh` 3. Add a leading `on` - `on`, `Before`, `Dom`, `Refresh` 4. Mash it into a single call - `onBeforeDomRefresh` Using this process, `before:dom:refresh` will call the `onBeforeDomRefresh` method. Let's see it in action with a custom event: ```javascript import { View } from 'marionette'; const MyView = View.extend({ onMyEvent(myVal) { console.log(myVal); } }); const myView = new MyView(); myView.triggerMethod('my:event', 'someValue'); // Logs 'someValue' ``` As before, all arguments passed into `triggerMethod` after the event name will make their way into the event handler. `triggerMethod` does not establish or clean up subscriptions; use `listenTo` and owner teardown, or explicit `off`, for listener cleanup. ### View `events` and `triggers` Views can automatically bind DOM events to methods and View events with [`events`](/docs/dom-interactions.md#view-events) and [`triggers`](/docs/dom-interactions.md#view-triggers) respectively: ```javascript import { View } from 'marionette'; const MyView = View.extend({ events: { 'click a': 'showModal' }, triggers: { 'keyup input': 'data:entered' }, showModal(event) { console.log('Show the modal'); }, onDataEntered(view, event) { console.log('Data was entered'); } }); ``` For more information, see the [DOM interactions documentation](/docs/dom-interactions.md#canonical-view-interaction). ### View entity events Views can automatically bind to its model or collection with [`modelEvents`](/docs/entity-events.md) and [`collectionEvents`](/docs/entity-events.md) respectively. ```javascript import { View } from 'marionette'; const MyView = View.extend({ modelEvents: { 'change:someattribute': 'onChangeSomeattribute' }, collectionEvents: { 'update': 'onCollectionUpdate' }, onChangeSomeattribute() { console.log('someattribute was changed'); }, onCollectionUpdate() { console.log('models were added or removed in the collection'); } }); ``` For more information, see the [Entity events documentation](/docs/entity-events.md). ## Child View Events The [`View`](/docs/view.md) and [`CollectionView`](/docs/collection-view.md) can handle events from their direct managed children through `childViewEvents`, forward selected names through `childViewTriggers`, or opt into a prefix through `childViewEventPrefix`. Without one of those configurations, a parent does not automatically forward every child event. For example: ```javascript import { View, CollectionView } from 'marionette'; const ChildView = View.extend({ tagName: 'li', template: () => '
    Select', triggers: { 'click a': 'select:model' } }); const ListView = CollectionView.extend({ tagName: 'ul', childView: ChildView, childViewEvents: { 'select:model': 'modelSelected' }, modelSelected(childView) { console.log('model selected: ' + childView.model.id); } }); const list = new ListView({ collection: [{ id: 'example' }] }).render(); list.el.querySelector('a').click(); // Logs 'model selected: example' ``` ### Event Bubbling Set `childViewEventPrefix: 'childview'` on a parent to forward every child event as `childview:`. The default is `false`, so prefixed forwarding is opt-in. Explicit `childViewEvents` and `childViewTriggers` still work when the prefix is disabled. Both `trigger` and `triggerMethod` events can be forwarded. The parent's matching method runs before its event listeners. Each level must configure the forwarding it needs. Arguments pass through unchanged: Marionette does not prepend the child instance to arbitrary events. DOM `triggers` already supply `(view, event)`, while a custom event must explicitly supply its View when handlers need it. ```javascript import { View } from 'marionette'; const MyView = View.extend({ template: false, triggers: { click: 'click:view' }, doSomething() { this.triggerMethod('did:something', this); } }); const ParentView = View.extend({ template: () => '
    ', childViewEventPrefix: 'childview', regions: { foo: '.foo-hook' }, onRender() { this.showChildView('foo', new MyView()); }, onChildviewClickView(childView) { console.log('View clicked ' + childView); }, onChildviewDidSomething(childView) { console.log('Something was done to ' + childView); } }); ``` **NOTE** `triggers` will automatically pass the child view as an argument to the parent view, however `triggerMethod` will not, and so notice that in the above example, the `triggerMethod` explicitly passes the child view. #### Using `CollectionView` The same opt-in applies to a `CollectionView` and its `childView`: ```javascript import { View, CollectionView } from 'marionette'; const MyChild = View.extend({ template: false, triggers: { click: 'click:child' } }); const MyList = CollectionView.extend({ childView: MyChild, childViewEventPrefix: 'childview', onChildviewClickChild(childView) { console.log('Childview ' + childView + ' was clicked'); } }); ``` ### A Child View's Event Prefix You can customize the event prefix for events that are forwarded through the view. To do this, set the `childViewEventPrefix` on the view or collectionview. For more information on the `childViewEventPrefix` see [Event bubbling](#event-bubbling). The default value for `childViewEventPrefix` is `false`. It disables prefixed forwarding, while explicit child event maps remain active. ```javascript import { CollectionView, View } from 'marionette'; const MyChildView = View.extend({ template: () => 'Child' }); const MyCollectionView = CollectionView.extend({ childViewEventPrefix: 'some:prefix', childView: MyChildView }); const collectionView = new MyCollectionView({ collection: [{}] }); collectionView.on('some:prefix:render', childView => { console.log('Child rendered', childView); }); collectionView.render(); ``` The `childViewEventPrefix` can be provided in the view definition or in the constructor function call, to get a view instance. ### Explicit Event Listeners To call specific functions on event triggers, use the `childViewEvents` attribute to map child events to methods on the parent view. This takes events fired on child views - _without the `childview:` prefix_ - and calls the method referenced or attached function. ```javascript import { View } from 'marionette'; const MyView = View.extend({ template: false, triggers: { click: 'view:clicked' } }); const ParentView = View.extend({ template: () => '
    ', regions: { foo: '.foo-hook' }, childViewEvents: { 'view:clicked': 'displayMessage' }, onRender() { this.showChildView('foo', new MyView()); }, displayMessage(childView) { console.log('Displaying message for ' + childView); } }); ``` #### Attaching Functions The `childViewEvents` attribute can also attach functions directly to be event handlers: ```javascript import { View } from 'marionette'; const MyView = View.extend({ template: false, triggers: { click: 'view:clicked' } }); const ParentView = View.extend({ template: () => '
    ', regions: { foo: '.foo-hook' }, childViewEvents: { 'view:clicked'(childView) { console.log('Function called for ' + childView); } }, onRender() { this.showChildView('foo', new MyView()); } }); ``` #### Using `CollectionView`'s `childViewEvents` ```javascript import { CollectionView } from 'marionette'; // childViewEvents can be specified as a hash... const MyCollectionView = CollectionView.extend({ childViewEvents: { // This callback will be called whenever a child is rendered or emits a `render` event render() { console.log('A child view has been rendered.'); } } }); ``` ### Triggering Events on Child Events A `childViewTriggers` hash or method permits proxying of child view events without manually setting bindings. Each own map key selects a child event, and its value names the event to trigger on the parent. Inherited entries are ignored. `childViewEvents` also normalizes only own enumerable string keys. `childViewTriggers` is sugar on top of [`childViewEvents`](#explicit-event-listeners) much in the same way that [view `triggers`](/docs/dom-interactions.md#view-triggers) are sugar for [view `events`](/docs/dom-interactions.md#view-events). ```javascript import { View, CollectionView } from 'marionette'; // The child view fires a custom event, `show:message` const ChildView = View.extend({ template: () => '
    ', // Events hash defines local event handlers that in turn may call `triggerMethod`. events: { 'click .button': 'onClickButton' }, triggers: { 'submit form': 'submit:form' }, onClickButton () { // Both `trigger` and `triggerMethod` events will be caught by parent. this.trigger('show:message', 'foo'); this.triggerMethod('show:message', 'bar'); } }); // The parent forwards the child's event through childViewTriggers. const ParentView = CollectionView.extend({ childView: ChildView, childViewTriggers: { 'show:message': 'child:show:message', 'submit:form': 'child:submit:form' }, onChildShowMessage (message) { console.log('A child view fired show:message with ' + message); }, onChildSubmitForm (childView) { console.log('A child view fired submit:form'); } }); const GrandParentView = View.extend({ template: () => '
    ', regions: { list: '.list' }, onRender() { this.showChildView('list', new ParentView({ collection: this.collection })); }, childViewEvents: { 'child:show:message': 'showMessage' }, showMessage(message) { console.log('A child sent: ' + message); } }); ``` #### Using `CollectionView`'s `childViewTriggers` ```javascript import { View, CollectionView } from 'marionette'; // The child view fires a custom event, `show:message` const ChildView = View.extend({ template: () => '
    ', // Events hash defines local event handlers that in turn may call `triggerMethod`. events: { 'click .button': 'onClickButton' }, // Triggers hash converts DOM events directly to view events catchable on the parent. // Note that `triggers` automatically pass the first argument as the child view. triggers: { 'submit form': 'submit:form' }, onClickButton () { // Both `trigger` and `triggerMethod` events will be caught by parent. this.trigger('show:message', 'foo'); this.triggerMethod('show:message', 'bar'); } }); // The parent forwards the child's event through childViewTriggers. const ParentView = CollectionView.extend({ childView: ChildView, childViewTriggers: { 'show:message': 'child:show:message', 'submit:form': 'child:submit:form' }, onChildShowMessage (message) { console.log('A child view fired show:message with ' + message); }, onChildSubmitForm (childView) { console.log('A child view fired submit:form'); } }); ``` ## Lifecycle Events Marionette Views fire events during their creation and destruction lifecycle. For more information see the documentation covering the [`View` Lifecycle](/docs/lifecycle.md). [Canonical source](/docs/markdown/docs/events.md) · [Source identity](/docs/manifest.json) --- Document: docs/events.class.md Canonical URL: https://marionettejs.com/docs/class-events/ Markdown URL: https://marionettejs.com/docs/class-events.md Reading SHA-256: cb7f4384ed8b3aa6446122cbd6924689564d3639ffbab50c753c138c765b26fc # Class Events Class events let you respond as a view renders, a Region shows a view, or an Application starts and stops. Marionette uses [`triggerMethod`](/docs/events.md#triggermethod) to dispatch these events, so you can listen to an event or define its matching [`onEvent` method](/docs/events.md#onevent-binding). Arguments depend on the event. Use the signatures below rather than assuming the first argument is the instance that triggered it; for example, a Behavior's proxied view events receive the host view. ## Documentation Index * [Application Events](#application-events) * [`before:start` event](#beforestart-event) * [`start` event](#start-event) * [`before:stop` event](#beforestop-event) * [`stop` event](#stop-event) * [Behavior Events](#behavior-events) * [`initialize` event](#initialize-event) * [Proxied Events](#proxied-events) * [Region Events](#region-events) * [`show` and `before:show` events](#show-and-beforeshow-events) * [`empty` and `before:empty` events](#empty-and-beforeempty-events) * [MnObject Events](#mnobject-events) * [View Events](#view-events) * [`add:region` and `before:add:region` events](#addregion-and-beforeaddregion-events) * [`remove:region` and `before:remove:region` events](#removeregion-and-beforeremoveregion-events) * [CollectionView Events](#collectionview-events) * [`add:child` and `before:add:child` events](#addchild-and-beforeaddchild-events) * [`remove:child` and `before:remove:child` events](#removechild-and-beforeremovechild-events) * [`sort` and `before:sort` events](#sort-and-beforesort-events) * [`filter` and `before:filter` events](#filter-and-beforefilter-events) * [`render:children` and `before:render:children` events](#renderchildren-and-beforerenderchildren-events) * [`destroy:children` and `before:destroy:children` events](#destroychildren-and-beforedestroychildren-events) * [CollectionView EmptyView Region Events](#collectionview-emptyview-region-events) * [DOM Change Events](#dom-change-events) * [`render` and `before:render` events](#render-and-beforerender-events) * [`attach` and `before:attach` events](#attach-and-beforeattach-events) * [`detach` and `before:detach` events](#detach-and-beforedetach-events) * [`dom:refresh` event](#domrefresh-event) * [`dom:remove` event](#domremove-event) * [Advanced Event Settings](#advanced-event-settings) * [Destroy Events](#destroy-events) * [`destroy` and `before:destroy` events](#destroy-and-beforedestroy-events) * [Wrapping legacy views](#wrapping-legacy-views) ## Application Events Application events describe its asynchronous lifecycle. Use a readiness method when completion must wait for work; event-listener return values are not awaited. ### `before:start` event Receives `(application, options, context)` before startup completes. The matching `onBeforeStart(application, options, { signal })` method may return a Promise to delay readiness. Pass the signal to cancellable work and prevent stale results from committing application side effects. ### `start` event Receives `(application, options)` after readiness and owned child startup complete. The matching `onStart(application, options)` method can show the feature's View. Both are completion notifications; their return values are not awaited. Use the [Application lifecycle example](/docs/application.md#starting-an-application) for startup and the [routing guide](/docs/routing.md) to connect an application's router. Starting a history service is application setup, not a Marionette lifecycle requirement. The `options` passed to a lifecycle operation reach its hooks and events. Readiness hooks and `before:*` events also receive a context whose signal is aborted when a later operation invalidates that readiness. A transferred stop phase retains its original options, context, and un-aborted signal. Only a Promise returned by `onBeforeStart`, `onBeforeStop`, or `onBeforeDestroy` delays its phase. See [Application lifecycle](/docs/application.md#application-lifecycle) for operation results, ordering, and cancellation. ### `before:stop` event Fired just before the application is stopped. A Promise returned by `onBeforeStop` delays completion of the stop lifecycle. ### `stop` event Fired after the application has stopped. This event is a completion notification and its return value is not awaited. #### Application `destroy` events The `Application` class also triggers `before:destroy` and `destroy` as part of its [asynchronous lifecycle](/docs/application.md#application-lifecycle). `onBeforeDestroy` is awaited and receives `(application, options, context)`; `onDestroy` is a completion notification and receives `(application, options)`. ## Behavior Events ### `initialize` event After the view and behavior are [constructed and initialized](/docs/behavior.md#initialize-order), the last event to occur is an `initialize` event on the behavior which is passed the view instance and any options passed to the view at instantiation. ```javascript import { Behavior, View } from 'marionette'; const MyBehavior = Behavior.extend({ onInitialize(view, options) { console.log(options.msg); } }); const MyView = View.extend({ behaviors: [MyBehavior] }); const myView = new MyView({ msg: 'view initialized' }); ``` **Note** This event is unique in that the triggering class instance (the view) is not the same instance as the handler (the behavior). In most cases internally triggered events are triggered and handled by the same instance, but this is an exception. ### Proxied Events A `Behavior`'s view events [are proxied directly on the behavior](/docs/behavior.md#proxy-handlers). **Note** In order to prevent conflict `Behavior` does not trigger [destroy events](#destroy-and-beforedestroy-events) with its own destruction. A `destroy` event occurring on the `Behavior` will have originated from the related view. ## Region Events When you show a view inside a region - either using [`region.show(view)`](/docs/region.md#showing-a-view) or [`showChildView('region', view)`](/docs/view.md#showing-a-child-view) - the `Region` will emit events around the view events that you can hook into. The `Region` class also triggers [Destroy Events](#destroy-and-beforedestroy-events). ### `show` and `before:show` events These events fire before (`before:show`) and after (`show`) showing anything in a region. A view may or may not be rendered during `before:show`, but a view will be rendered by `show`. The `show` events will receive the region instance, the view being shown, and any options passed to `region.show`. ```javascript import { Region, View } from 'marionette'; const MyRegion = Region.extend({ onBeforeShow(myRegion, view, options) { console.log(myRegion.hasView()); //false console.log(view.isRendered()); // false console.log(options.foo === 'bar'); // true }, onShow(myRegion, view, options) { console.log(myRegion.hasView()); //true console.log(view.isRendered()); // true console.log(options.foo === 'bar'); // true } }); const MyView = View.extend({ template: () => 'hello' }); const regionElement = document.createElement('div'); const myRegion = new MyRegion({ el: regionElement }); myRegion.show(new MyView(), { foo: 'bar' }); ``` ### `empty` and `before:empty` events These events fire before (`before:empty`) and after (`empty`) emptying a region's view. These events will not fire if there is no view in the region, even if the region detaches DOM from within the region's `el`. The view will not be detached or destroyed during `before:empty`, but will be detached or destroyed during the `empty`. The empty events will receive the region instance, the view leaving the region. ```javascript import { Region, View } from 'marionette'; const MyRegion = Region.extend({ onBeforeEmpty(myRegion, view) { console.log(myRegion.hasView()); //true console.log(view.isDestroyed()); // false }, onEmpty(myRegion, view) { console.log(myRegion.hasView()); //false console.log(view.isDestroyed()); // true } }); const MyView = View.extend({ template: () => 'hello' }); const regionElement = document.createElement('div'); const myRegion = new MyRegion({ el: regionElement }); myRegion.empty(); // no events, no view emptied myRegion.show(new MyView()); myRegion.empty(); ``` ## MnObject Events The `MnObject` class triggers [Destroy Events](#destroy-and-beforedestroy-events). ## View Events ### `add:region` and `before:add:region` events These events fire before (`before:add:region`) and after (`add:region`) a region is added to a view. This event handler will receive the view instance, the region name string, and the region instance as event arguments. The Region is fully instantiated for both events. ### `remove:region` and `before:remove:region` events These events fire before (`before:remove:region`) and after (`remove:region`) a region is removed from a view. This event handler will receive the view instance, the region name string, and the region instance as event arguments. The Region is not yet destroyed in the before event, but is destroyed by `remove:region`. `removeRegion()` and the View's Region cleanup path emit these events. Destroying a Region directly does not itself emit the owning View's remove-region events. ## CollectionView Events The `CollectionView` triggers unique events specifically related to child management. ### `add:child` and `before:add:child` events These events fire before (`before:add:child`) and after (`add:child`) each child View is added to [`children`](/docs/collection-view.md#accessing-a-child-view). Both receive `(collectionView, childView)`; the child is already constructed at `before:add:child`. These will fire once for each model in the attached collection or for any view added using [`addChildView`](/docs/collection-view.md#adding-a-child-view). ### `remove:child` and `before:remove:child` events These events fire before (`before:remove:child`) and after (`remove:child`) each child view is removed from the [`children`](/docs/collection-view.md#accessing-a-child-view). A view may be removed from the `children` if it is destroyed, if it is removed from the `collection` or if it is removed with [`removeChildView`](/docs/collection-view.md#removing-a-child-view). **NOTE** A childview may or may not be destroyed by this point. **NOTE** When a `CollectionView` is destroyed it will not individually remove its `children`. Each childview will be destroyed, but any needed clean up during the `CollectionView`'s destruction should happen in [`before:destroy:children`](#destroychildren-and-beforedestroychildren-events). ### `sort` and `before:sort` events These events fire before (`before:sort`) and after (`sort`) sorting the children in the `CollectionView`. These events fire when there are managed children and `getComparator()` returns an active comparator, including the default comparator for collection order. See [`viewComparator`](/docs/collection-view.md#defining-the-viewcomparator). ### `filter` and `before:filter` events These events fire before (`before:filter`) and after (`filter`) filtering the children in the `CollectionView`. This event will only fire if there are [`children`](/docs/collection-view.md#accessing-a-child-view) and a [`viewFilter`](/docs/collection-view.md#defining-the-viewfilter). When the `filter` event is fired the children filtered out will have already been detached from the view's `el`, but new children will not yet have been rendered. The `filter` event receives `(collectionView, passingViews, filteredViews)`. Passing Views are the selected result; some may already be attached, while new ones are rendered and attached by the following child-render pass. ```javascript import { CollectionView } from 'marionette'; const MyCollectionView = CollectionView.extend({ onBeforeFilter(myCollectionView) { console.log('Nothing has changed yet!'); }, onFilter(myCollectionView, passingViews, filteredViews) { console.log('Views passing the filter', passingViews); console.log('Views excluded by the filter', filteredViews); } }); ``` ### `render:children` and `before:render:children` events Similar to [`Region` `show` and `before:show` events](#show-and-beforeshow-events) these events fire before (`before:render:children`) and after (`render:children`) the `children` of the `CollectionView` are attached to the `CollectionView`'s `el` or `childViewContainer`. These events will be passed the `CollectionView` instance and the array of views being attached. The views in the array may or may not be rendered or attached for `before:render:children`, but will be rendered and attached by `render:children`. Both events receive the complete current presented `children` array, including already-rendered survivors. An empty result still emits both events with an empty array while the empty-View Region is updated. “Attached” here means inserted into the CollectionView container; the container itself may be detached from the document. ### `destroy:children` and `before:destroy:children` events These events fire before (`before:destroy:children`) and after (`destroy:children`) destroying the children in the `CollectionView`. These events will only fire if there are [`children`](/docs/collection-view.md#accessing-a-child-view). ### CollectionView EmptyView Region Events The `CollectionView` uses a Region internally to show or destroy its empty View. See [Region Events](#region-events). ```javascript import { CollectionView, View } from 'marionette'; const MyEmptyView = View.extend({ template: () => 'No items' }); const MyView = CollectionView.extend({ emptyView: MyEmptyView }); const myView = new MyView(); myView.getEmptyRegion().on({ 'show'() { console.log('CollectionView is empty!'); }, 'before:empty'() { if (this.hasView()) { console.log('CollectionView is removing the emptyView'); } } }); myView.render(); ``` ## DOM Change Events ### `render` and `before:render` events For `View`, these events bracket template rendering. For `CollectionView`, they bracket the complete child rebuild/render pass, even without a template. Both receive the instance as their argument. `before:render` will occur prior to removing any current child views. `render` is an ideal event for attaching child views to the view's template as the first render _generally_ occurs prior to the view attaching to the DOM. ```javascript import { View, CollectionView } from 'marionette'; const MyChildView = View.extend({ template: () => 'Child' }); const MyView = View.extend({ template: () => '
    ', regions: { 'foo': '.foo-region' }, onRender() { this.showChildView('foo', new MyChildView()); } }); const MyCollectionView = CollectionView.extend({ childView: MyChildView, onRender() { // Add a child not from the `collection` this.addChildView(new MyChildView()); } }) ``` Adopting [prerendered contents](/docs/prerendered-dom.md) does not itself emit these events. Use `initialize` for initial child setup on that path. `View#render()` returns without events when `template` is `false`; `CollectionView#render()` still emits its render events when its template is `false` or absent. ### `attach` and `before:attach` events Reflects when the `el` of a view is attached to the DOM. These events will not trigger when a view is re-rendered as the `el` itself does not change. `attach` is the ideal event to setup any external DOM listeners such as `jQuery` plugins that use the view's `el`, but _not_ its contents. ### `detach` and `before:detach` events Reflects when the `el` of a view is detached from the DOM. These events will not trigger when a view is re-rendered as the `el` itself does not change. `before:detach` is the ideal event to clean up any external DOM listeners such as `jQuery` plugins that use the view's `el`, but _not_ its contents. ### `dom:refresh` event Reflects when the _contents_ of a view's `el` change in the DOM. This event will fire when the view is first [`attach`ed](#attach-and-beforeattach-events). It will also fire if an attached view is re-rendered. This is the ideal event to setup any external DOM listeners such as `jQuery` plugins that use DOM _within_ the `el` of the view and not the view's `el` itself. The monitor requires both `isAttached()` and `isRendered()` to be true. Prerendered contents can establish rendered state, and a CollectionView render establishes it even without a template. ### `dom:remove` event Reflects when the _contents_ of a view's `el` are about to change in the DOM. This event will fire when the view is about to be [`detach`ed](#detach-and-beforedetach-events). It will also fire before an attached view is re-rendered. This is the ideal event to clean up any external DOM listeners such as `jQuery` plugins that use DOM _within_ the `el` of the view and not the view's `el` itself. The monitor requires both `isAttached()` and `isRendered()` to be true. Prerendered contents can establish rendered state, and a CollectionView render establishes it even without a template. ### Advanced Event Settings Marionette is able to trigger `attach`/`detach` events down the view tree along with triggering the `dom:refresh`/`dom:remove` events because of the view event monitor. This monitor starts when a Marionette View is constructed. In some cases it may be a useful performance improvement to disable this functionality. Doing so is as easy as setting `monitorViewEvents: false` on the view class. ```javascript import { View } from 'marionette'; const NonMonitoredView = View.extend({ monitorViewEvents: false }); ``` **Note**: Disabling the view monitor will break the monitor generated events for this view _and all child views_ of this view. Disabling should be done carefully. ## Destroy Events ### `destroy` and `before:destroy` events Every class has a `destroy` method which can be used to clean up the instance. With the exception of `Behavior`, each class triggers a `before:destroy` and a `destroy` event. Application uses the separate asynchronous lifecycle described under [Application Events](#application-events); this section describes the synchronous owner classes. As a general rule, `onBeforeDestroy` is the best handler for cleanup as the instance and any internally created children are already destroyed by the time `onDestroy` is called. For classes with these lifecycle events, once destruction begins, reentrant `destroy()` calls from `before:destroy` or `destroy`, and later repeated calls, return the same instance without restarting teardown. `isDestroyed()` remains `false` during `before:destroy` and is `true` by the time `destroy` is triggered. If a synchronous lifecycle handler throws, its error propagates and teardown stops. Later `destroy()` calls do not retry the lifecycle or resume partial cleanup. Application's asynchronous operation failures follow its separate lifecycle contract. Use [`dom:remove`](#domremove-event) or [`before:detach`](#detach-and-beforedetach-events) for work tied to those transitions. Resources created while detached, or while attachment monitoring is disabled, also need owner cleanup in `onBeforeDestroy`; do not rely on a DOM notification that may never occur. ```javascript import { View } from 'marionette'; const MyView = View.extend({ onBeforeDestroy(view, options) { console.log(options.foo); } }); const myView = new MyView(); myView.destroy({ foo: 'destroy view' }); ``` #### `CollectionView` `destroy:children` and `before:destroy:children` events Similar to `destroy`, `CollectionView` has events for when all of its children are destroyed. See [the CollectionView's events](#destroychildren-and-beforedestroychildren-events) for more information. ## Wrapping legacy views Managed children provide Marionette's render and destroy lifecycle themselves. `supportsRenderLifecycle` and `supportsDestroyLifecycle` are removed; Regions and CollectionViews do not supply missing lifecycle events or call `remove()` as a substitute for `destroy()`. Keep non-Marionette views inside a [Marionette wrapper](/docs/region.md#wrapping-a-non-marionette-view) that owns their rendering and cleanup. Mixing `Marionette.Events` into a Backbone View does not make it a supported managed child. [Canonical source](/docs/markdown/docs/events.class.md) · [Source identity](/docs/manifest.json) --- Document: docs/events.entity.md Canonical URL: https://marionettejs.com/docs/entity-events/ Markdown URL: https://marionettejs.com/docs/entity-events.md Reading SHA-256: 63ba9a71b1af96e01d52a5d8728348872f600b80553144afca5258d5af5e77e4 # Entity events [`View`, `CollectionView`, and `Behavior`](/docs/classes.md) can declaratively listen to events from an attached `model` or `collection`. The configured [`DataApi.subscribe()`](/docs/data-api.md#adapter-contract) owns the entity's subscription and teardown mechanics; Backbone is optional. ## Handler ownership and arguments `modelEvents` and `collectionEvents` map entity event names to method names or function callbacks. Entity arguments pass through unchanged. - A View or CollectionView handler runs with that View or CollectionView as `this`. - A Behavior listens to its owning View's `model` and `collection`, but its handler runs with the Behavior as `this`. Use `this.view` to reach the owner. ```javascript import { Behavior, Events, View } from 'marionette'; class Model {} Object.assign(Model.prototype, Events); const StatusBehavior = Behavior.extend({ modelEvents() { this.modelEventsResolutionCount = (this.modelEventsResolutionCount || 0) + 1; return { 'change:status': 'onStatus' }; }, onStatus(model, status) { this.view.behaviorCall = { arguments: [model, status], owner: this }; } }); const StatusView = View.extend({ behaviors: [StatusBehavior], modelEvents() { this.modelEventsResolutionCount = (this.modelEventsResolutionCount || 0) + 1; return { 'change:status': 'onStatus' }; }, onStatus(model, status) { this.viewCall = { arguments: [model, status], owner: this }; } }); const model = new Model(); const view = new StatusView({ model }); model.trigger('change:status', model, 'ready'); export { Model, model, view }; ``` Function callbacks are also supported directly. This configuration fragment uses the `update(collection, options)` payload from Backbone or `@mnjs/data`; configure the matching DataApi before supplying that collection: ```javascript import { View } from 'marionette'; const MyView = View.extend({ collectionEvents: { update(collection, options) { console.log('Added models:', options.changes.added); } } }); ``` If a View has both entities, Marionette delegates both maps: ```javascript import { View } from 'marionette'; const MyView = View.extend({ modelEvents: { 'change:status': 'render' }, collectionEvents: { update: 'render' } }); ``` ## Resolver and delegation lifecycle Each map may be a function returning an object. Marionette calls the resolver with its owner as `this` and no arguments whenever `delegateEntityEvents()` performs a delegation. The resolved map is cached for the matching `undelegateEntityEvents()` call. Initial entity-event delegation happens after the View or CollectionView's `initialize` method returns. Assigning a different `model` or `collection` later does not automatically move existing subscriptions. Undelegate while the old entity is still assigned, replace it, and then delegate the new entity: ```javascript view.undelegateEntityEvents(); view.model = replacementModel; view.delegateEntityEvents(); ``` Do not use repeated `delegateEntityEvents()` calls as an idempotent refresh; delegate only after the matching undelegation. After a View or CollectionView's destruction completes successfully, its tracked entity subscriptions have been removed. Once destruction starts, its base `delegateEntityEvents()` returns the same instance without resolving its maps or delegating the attached Behaviors' maps. A direct `Behavior#delegateEntityEvents()` call also returns the Behavior without resolving maps or binding once its owning View's destruction starts. These guards derive from the host lifecycle only; reusing a Behavior after calling `Behavior#destroy()` while its host remains live is outside this contract. A custom override owns its behavior unless it delegates to the guarded base method. `undelegateEntityEvents()` remains available during teardown so cleanup can complete. ## Event-map names Entity-event maps cannot contain an own enumerable `__proto__` event name. Marionette throws `MarionetteError` code `MN0026` before binding or selectively unbinding such a map because third-party entity event implementations may not safely store that name. Marionette does not reject other names inherited from `Object.prototype`, such as `constructor` and `toString`. Marionette's Events API supports those names and continues to support `__proto__`, but third-party emitters may not safely support every prototype-collision name. ## Backbone entities A plain `Backbone.Model` or `Backbone.Collection` satisfies the default subscription protocol for event-only use. The canonical Backbone setup configures the integration before constructing Marionette consumers; it also selects Backbone identity, reads, serialization, ordered model snapshots, and structural observations: ```javascript import BackboneApi from '@mnjs/adapters/backbone'; import Backbone from 'backbone'; import { setDataApi, View } from 'marionette'; setDataApi(BackboneApi); const model = new Backbone.Model(); const view = new View({ model }); ``` See [Optional Backbone](/docs/backbone.md) for the integration's exact boundary. [Canonical source](/docs/markdown/docs/events.entity.md) · [Source identity](/docs/manifest.json) --- Document: docs/radio.md Canonical URL: https://marionettejs.com/docs/radio/ Markdown URL: https://marionettejs.com/docs/radio.md Reading SHA-256: 0c53fa2091a01f0d52c2ea9c1712dc543ef77dd2a83da10087265f34d38e750b # Radio Use `Radio` to send events or request values between parts of an application that do not need a direct reference to each other. Channels keep those messages organized by name. Import Radio directly from Marionette: ```javascript import { Radio } from 'marionette'; ``` Radio is included in `marionette`; it does not require a separate `backbone.radio` installation. The built-in singleton does not share channels with `backbone.radio`. Migrate all application imports atomically, including code that publishes or requests outside Marionette classes; mixing both packages creates disconnected buses. See [Atomic Radio migration](/docs/upgrade-guide.md#atomic-radio-migration). ## Documentation Index * [Channels](#channels) * [Events](#events) * [Requests and Replies](#requests-and-replies) * [Debugging](#debugging) * [Channel Lifecycle](#channel-lifecycle) * [Marionette Integration](#marionette-integration) ## Channels A channel provides a namespace for events and requests. Retrieve one with `Radio.channel(name)`: ```javascript import { Radio } from 'marionette'; const notifications = Radio.channel('notifications'); ``` Calling `Radio.channel(name)` again with the same name returns the same channel instance. A channel name is required. Channel names that match inherited object properties, such as `toString`, are treated as ordinary channel names. Use `new Channel(name)` from `@mnjs/radio` for an independent message bus. It combines Events and Requests but does not join the registry. Its owner must call `channel.reset()` when finished. `Radio.reset()` covers registered channels. The named `Channel` export is `Radio.Channel`; an isolated runtime provides its own constructor at `runtime.Radio.Channel`. For request/reply alone, import `Requests` from `@mnjs/radio` and compose it with `Object.assign({}, Requests)`. It adds no event methods or registry. ## Events Channels provide event-style messaging with methods including `on`, `once`, `off`, `trigger`, `listenTo`, and `stopListening`. ```javascript import { Radio } from 'marionette'; const session = Radio.channel('session'); session.on('expired', function(reason) { console.log(`Session expired: ${ reason }`); }); session.trigger('expired', 'signed out remotely'); session.off('expired'); ``` Use events when zero or more listeners may react to a notification and the sender does not need a return value. ## Requests and Replies Channels also provide request/reply messaging. Register one reply with `reply`, then call it with `request`: ```javascript import { Radio } from 'marionette'; const account = Radio.channel('account'); const accountService = { currentUser: { id: 'example' } }; account.reply('current:user', function() { return this.currentUser; }, accountService); const currentUser = account.request('current:user'); ``` Arguments passed after the request name are passed to the reply handler, and the handler's return value is returned from `request`. Invocation is synchronous: a thrown error reaches the caller immediately; a returned Promise is passed through unchanged and must be awaited or handled by the caller. Radio does not add cancellation, retries, or error handling. A named handler takes precedence over a handler registered as `default`. The default handler receives `(requestName, ...args)`. With neither handler, `request` returns `undefined` and may emit a debug warning. A non-function value registered with `reply(name, value)` is returned as-is for each request. Registering a second reply for the same name replaces the first; it does not multicast the request. `reply`, `replyOnce`, and `stopReplying` return the channel or Requests receiver. A `replyOnce` handler is removed before invocation, including when it throws or makes a reentrant request. Removing it by its original callback before invocation also cancels it. Choose ordinary events when several independent listeners need to react to the same notification. Only explicitly registered own handlers are eligible for a named request or the `default` fallback. Names matching inherited object properties, including `constructor`, `toString`, and `__proto__`, are ordinary request names. Result maps from object-form or space-separated requests likewise define safe own string properties. When an object-form key contains multiple space-separated names, the nested result contributes its own enumerable string and symbol properties; inherited and non-enumerable properties are ignored. Use `replyOnce` for a handler that should be removed after its first request. Use `stopReplying` to remove one or more handlers: ```javascript account.replyOnce('status:ready', () => true); account.stopReplying('current:user'); ``` The request registration methods retain Backbone.Radio's customization seams: `replyOnce` installs its wrapper through overridable `reply`, and map or space-separated `reply`, `replyOnce`, and `stopReplying` calls dispatch each entry through the corresponding public method. For object-form `request`, the mapped value is the first handler argument and any arguments after the map are forwarded after it. Use requests when one handler owns an operation or when the sender needs a return value. ## Debugging Enable Radio debug warnings with `setDebug`: ```javascript import { Radio } from 'marionette'; Radio.setDebug(); ``` Debug mode warns when a request handler is overwritten or an unhandled request is made. Disable it explicitly when it is no longer needed: ```javascript Radio.setDebug(false); ``` `Radio.log(channelName, eventName, ...args)` receives activity from `tuneIn()`. `Radio.debugLog(warning, eventName, channelName)` receives warnings while debug mode is enabled. Assign either hook to route output to an application logger or test collector. Both default to console output. ```javascript import { createMarionette } from 'marionette'; const runtime = createMarionette(); runtime.Radio.debugLog = (warning, eventName, channelName) => { console.warn({ warning, eventName, channelName }); }; runtime.Radio.setDebug(); ``` Hooks belong to each Radio instance and run with that Radio as `this`. Replacing a hook affects existing channels, including tuned channels. Disabling debug mode also disables delivery to custom warning hooks. Exceptions from hooks propagate. Standalone `Channel` and `Requests` imports use the default Radio's warning configuration; `new runtime.Radio.Channel(name)` uses that runtime's configuration. ## Channel Lifecycle Channels are shared by name within their Radio runtime and remain available for that runtime's lifetime. Root imports use one default Radio. Each [`createMarionette()`](/docs/runtime-isolation.md) call returns an isolated Radio and channel registry. Clean up handlers when their owning object or feature is destroyed: ```javascript import { MnObject, Radio } from 'marionette'; const owner = new MnObject(); const channel = Radio.channel('feature'); owner.stopListening(channel); channel.off(null, null, owner); channel.stopReplying(null, null, owner); ``` The matching cleanup depends on whether the owner used `listenTo`, `on`, or `reply` to register the handler. Call `channel.reset()` to remove all event listeners, listening relationships, and reply handlers from that channel. `Radio.reset(name)` resets one existing channel, while `Radio.reset()` resets all existing channels. Resetting a channel clears its handlers but does not replace the shared channel instance. Prefer targeted cleanup for long-lived application channels so one feature does not remove another feature's handlers. | Operation | Unknown channel | Existing channel | | --- | --- | --- | | `Radio.channel(name)` | Creates and registers the channel. | Returns the same channel. | | Top-level event, request, and tuning methods | Create the channel through `Radio.channel(name)`. | Operate on the same channel. | | `Radio.reset(name)` | Throws `MarionetteError` with code [MN0021](/docs/diagnostics.md#look-up-a-code) without creating a channel. | Clears handlers and preserves the channel identity. | | `Radio.reset()` | Does not create channels. | Resets every registered channel without replacing it. | Only a zero-argument `Radio.reset()` call means reset all. Supplying an empty or otherwise falsy channel name throws the existing required-name diagnostic [MN0017](/docs/diagnostics.md#look-up-a-code) without resetting any channel. ## Marionette Integration `Application` and `MnObject` can bind events and requests to a channel with `channelName`, `radioEvents`, and `radioRequests`. `getChannel()` returns the configured channel. `radioEvents` follows the [entity-event map contract](/docs/common.md#bindevents), including the `MN0026` rejection of an own enumerable `__proto__` map entry. The direct Radio Events API continues to support `__proto__` as an event name. ```javascript import { MnObject, Radio } from 'marionette'; export const Notifications = MnObject.extend({ channelName: 'notifications', initialize() { this.messages = []; }, radioEvents: { 'message:received': 'showMessage' }, radioRequests: { 'message:count': 'getMessageCount' }, showMessage(message) { this.messages.push(message); }, getMessageCount() { return this.messages.length; } }); export const notifications = new Notifications(); export const channel = Radio.channel('notifications'); const message = { text: 'Hello' }; channel.trigger('message:received', message); const count = channel.request('message:count'); ``` Destroying the Marionette object removes request handlers bound with that object as their context. The object's event listeners are cleaned up through the normal Marionette event lifecycle. ## Backbone.Radio comparison The v5 Radio implementation retains Backbone.Radio's channel messaging model, but it is not a drop-in replacement for every exported property. `@mnjs/radio` can be used independently; core re-exports the same default `Radio` within each module format. | Area | v5 behavior | | --- | --- | | Requests and replies | Named/default handlers, callback context, map and space-separated forms, one-time replies, and selective removal retain the messaging contract. | | Events and cleanup | Channels use shared Marionette Events. Reset clears handlers and owned listeners while retaining channel identity. Events also provides `triggerMethod`. | | Debugging | Use `setDebug()` instead of assigning `DEBUG`. `log` and `debugLog` are replaceable per-instance hooks, and the debug toggle gates custom warning hooks too. Removing an absent reply does not warn. | | Construction and globals | Use `channel(name)` for registered channels, `new Channel(name)` for standalone channels, or the named `Requests` mixin for request/reply alone. `VERSION`, Backbone global installation, and `noConflict()` are not Radio exports. | | Names and maps | Request maps use own enumerable string keys. Inherited entries are ignored; names such as `__proto__` are supported without changing object prototypes. | | Reset arguments | Only `reset()` resets all channels. An explicitly supplied empty name is an error; an unknown named channel gets a Marionette diagnostic. | `test/unit/radio-parity.spec.js` runs shared behavioral scenarios against the published Backbone.Radio 2.0.0 runtime and Marionette: fallback arguments, flat values, nested request maps, reentrant and throwing one-time handlers, callback and context removal, top-level forwarding, and channel/listener cleanup. The extraction was also checked against the upstream request, channel, forwarding, tuning, and debug tests at [Backbone.Radio commit 7a58ade](https://github.com/marionettejs/backbone.radio/tree/7a58ade84bedb5551c2e12bdd3434d0fd6b1bdbd/test/unit). That comparison adapts private registry names and the old debug toggle; tests requiring removed public APIs are differences, not claims of full compatibility. One intentional correction relative to the published 2.0.0 bundle is cancellation of `replyOnce` by its original callback: `stopReplying(name, callback)` removes the pending reply in v5. The published bundle and inspected upstream source leave it registered. This follows the callback-identity behavior of Backbone.Events `once`/`off`. The comparison test records the difference explicitly instead of claiming exact parity. [Canonical source](/docs/markdown/docs/radio.md) · [Source identity](/docs/manifest.json) --- Document: docs/utils.md Canonical URL: https://marionettejs.com/docs/utils/ Markdown URL: https://marionettejs.com/docs/utils.md Reading SHA-256: d7ea4080dad95c0bb3283a8461d569584b86e3f9cd7daa0faaa469798e3e777a # Marionette Utility Exports Marionette exports the standalone utilities and package facts that do not require a framework instance. Common framework conventions such as `bindEvents`, `getOption`, `mergeOptions`, `normalizeMethods`, and `triggerMethod` are documented as [instance methods](/docs/common.md). The v4 target-first exports also adapted these conventions to arbitrary plain objects. That adapter is not part of v5. Import reusable helpers from [`@mnjs/utils`](/docs/common.md#shared-helpers) when a plain component needs them; extend `MnObject` when it needs Marionette's initialization and cleanup lifecycle. Do not borrow a framework prototype solely to obtain a helper. ## Documentation Index * [extend](#extend) * [VERSION](#version) ## extend `extend` is Marionette's owned, standalone implementation of its classic pseudo-class extension convention. Assign it to a constructor, then call it as a method so that constructor is the parent. Marionette's extendable classes already expose this method. ```javascript import { extend } from 'marionette'; function Service(name) { this.name = name; } Service.extend = extend; const SpecialService = Service.extend({ label() { return `special:${this.name}`; } }, { kind: 'special' }); const service = new SpecialService('api'); export { Service, SpecialService, extend, service }; ``` The child inherits the parent's prototype and static properties. Prototype properties are supplied by the first argument and optional static properties by the second. See the [v4 compatibility ledger](/docs/migration-from-v4.md#compatibility-ledger) for the v5 input-copying boundary. ## VERSION `VERSION` is the installed Marionette package version. Marionette also uses it when constructing versioned diagnostic documentation URLs; exporting it does not imply that a corresponding website deployment is available. ```javascript import { VERSION } from 'marionette'; export { VERSION }; ``` [Canonical source](/docs/markdown/docs/utils.md) · [Source identity](/docs/manifest.json) --- Document: docs/marionette.mnobject.md Canonical URL: https://marionettejs.com/docs/mn-object/ Markdown URL: https://marionettejs.com/docs/mn-object.md Reading SHA-256: c92fd00483055350c4696082070a77361ec33fdc1b3d503e2a57175a1141e8d9 # Marionette.MnObject Use `MnObject` for objects that need Marionette events and cleanup without a DOM element. It provides `initialize`, options, the Events API, a unique `cid`, and `extend`, with no Backbone dependency. `MnObject` includes: - [Common Marionette Functionality](/docs/common.md) - [Class Events](/docs/class-events.md#mnobject-events) - [Radio API](/docs/radio.md#marionette-integration) - [State ownership](/docs/state.md#borrowed-and-owned-sources) ## Documentation Index * [Instantiating a MnObject](#instantiating-a-mnobject) * [Unique Client ID](#unique-client-id) * [Destroying a MnObject](#destroying-a-mnobject) * [Basic Use](#basic-use) * [v4 Migration](#v4-migration) ## Instantiating a MnObject Constructor options are shallow-copied into `this.options`. Own enumerable `channelName`, `radioEvents`, `radioRequests`, and `stateEvents` options with values other than `undefined` are also attached directly to the instance. Other options remain available through `this.options` and `getOption` unless explicitly merged. The channel options use Marionette's built-in [`Radio`](/docs/radio.md); see that guide for the separate `backbone.radio` migration boundary. A supplied `state` source is borrowed. A source returned by `createState(options)` is owned and created lazily; `getState()` returns the exact source. Configured `stateEvents` subscribe after `initialize`. Destruction removes those subscriptions and disposes owned State through the selected StateApi. See [State](/docs/state.md) before enabling observable State events. ```javascript import { MnObject } from 'marionette'; const myObject = new MnObject({ channelName: 'tasks' }); myObject.channelName; // 'tasks' ``` ## Unique Client ID The `cid` or client id is a unique identifier automatically assigned to MnObjects when they're first created and by default is prefixed with `mno`. You can modify the prefix for `MnObject`s you `extend` by setting the `cidPrefix`, which should be a non-empty string when customized. IDs generated with the same prefix by one loaded copy of Marionette are unique, including when different Marionette types use that prefix. Treat the complete `cid` as opaque: its numeric suffix and allocation order are not API, and its sequence is not coordinated with IDs generated by Underscore or Backbone. The [v4-to-v5 migration ledger](/docs/migration-from-v4.md#compatibility-ledger) records the sequence-ownership rationale. ```javascript import { MnObject } from 'marionette'; const MyFoo = MnObject.extend({ cidPrefix: 'foo' }); const foo = new MyFoo(); foo.cid.startsWith('foo'); // true ``` ## Destroying a MnObject ### `destroy` On successful completion of its lifecycle, `destroy` removes subscriptions the instance made with `listenTo`, releases its owned Radio event subscriptions and replies, cleans up State, and returns the MnObject synchronously. Returned Promises from destruction hooks are not awaited. It does not reset the shared Radio channel or remove unrelated channel handlers. Listeners registered directly on the instance with `on` are not removed automatically. If a lifecycle callback throws, cleanup that has not yet run may be skipped; the failure boundaries are described below. Invoking `destroy` triggers `before:destroy` and `destroy` events and their [corresponding `onBeforeDestroy` and `onDestroy` methods](/docs/events.md#onevent-binding). Each receives the MnObject followed by the `options` passed to `destroy`. While a `destroy()` call is in progress, nested calls from either lifecycle event return the same MnObject without restarting teardown. Calls after destruction also return the same MnObject without repeating the lifecycle. `Application` has an asynchronous destruction lifecycle; see its [reference](/docs/application.md#application-lifecycle). `isDestroyed()` is `false` during `before:destroy` and `true` during `destroy`. If a lifecycle handler throws, the error propagates and stops destruction. The destruction guard remains set; later `destroy()` calls do not restart hooks or resume cleanup. A custom override that mutates owned state before calling the base `destroy` method is outside this guard. See the [v4-to-v5 compatibility ledger](/docs/migration-from-v4.md#compatibility-ledger) for the override boundary. ```javascript import { MnObject } from 'marionette'; // define a mnobject with an onBeforeDestroy method const MyObject = MnObject.extend({ onBeforeDestroy(currentObject, options) { // put other custom clean-up code here } }); // create new MnObject instances const obj = new MyObject(); const source = new MnObject(); // add some event handlers obj.on('before:destroy', function(currentObject, options) { console.log(options.foo); }); obj.listenTo(source, 'bar', function() {}); // trigger the lifecycle and stop listening to source obj.destroy({ foo: 'bar' }); ``` ### `isDestroyed` This method will return a boolean indicating if the mnobject has been destroyed. ```javascript import { MnObject } from 'marionette'; const obj = new MnObject(); obj.isDestroyed(); // false obj.destroy(); obj.isDestroyed(); // true ``` ## Basic Use Selections is a simple MnObject that manages a selection of things. Because Selections extends from MnObject, it inherits `initialize` and the [Events API](/docs/events.md). ```javascript import { MnObject } from 'marionette'; const Selections = MnObject.extend({ initialize() { this.selections = {}; }, select(key, selection) { this.selections[key] = selection; this.triggerMethod('select', key, selection); }, deselect(key, selection) { delete this.selections[key]; this.triggerMethod('deselect', key, selection); } }); const selections = new Selections(); const truck = { name: 'Dump truck' }; // use the inherited Events API selections.on('select', function(key, selection) { console.log(selection); }); selections.select('toy', truck); ``` ## v4 Migration v5 exports `MnObject` by name from `marionette`. The historical `Object` alias and v4 default namespace export are removed. See the [v4-to-v5 migration ledger](/docs/migration-from-v4.md) for the replacement paths. [Canonical source](/docs/markdown/docs/marionette.mnobject.md) · [Source identity](/docs/manifest.json) --- Document: docs/diagnostic-catalog.md Canonical URL: https://marionettejs.com/docs/diagnostics/ Markdown URL: https://marionettejs.com/docs/diagnostics.md Reading SHA-256: 060b1d0808d63c1934369d6ee65814b670306d2370a7516702b58c37c58fbd6e # Diagnostic catalog Marionette uses one machine-readable catalog to identify framework invariants across runtime diagnostics, static analysis, development and test tooling, documentation, and the public agent benchmark. The catalog is stored in `config/diagnostics/catalog.json`, and its executable contract is `config/diagnostics/catalog.schema.json`. The catalog is static project metadata. Production entrypoints must not import the catalog, and the catalog is not part of the production package surface. Runtime diagnostics may embed a compact catalog code, but they must not load the full catalog. Schema version 2 adds explicit retired identities without restoring their emissions. ## Look up a code Read the [machine-readable catalog](/docs/source/config/diagnostics/catalog.json), find the entry by `code`, and read its `remediation`. This file is included in packaged docs for offline lookup. The website also provides a [diagnostic reference](/errors/index.md). ## Runtime error contract Framework invariant failures use the public `MarionetteError` class: ```javascript import { MarionetteError, View } from 'marionette'; try { new View({ template: false }).showChildView('missing', new View()); } catch (error) { if (error instanceof MarionetteError && error.code === 'MN0020') { // Handle the missing named Region. } } ``` `MarionetteError` extends the native `Error` class and exposes `name`, `code`, `message`, `stack`, and the existing `url` property. The code is the stable lookup key for the repository-generated diagnostic reference. Error names preserve useful framework categories such as `ViewError`, `RegionError`, and `CollectionViewError`. Messages and legacy URLs are explanatory prose and are not machine contracts. Production errors copy only supported Error fields and the compact code. They do not import the catalog or perform runtime catalog lookup. Engines with `Error.captureStackTrace` use it; other engines retain the native fallback stack. ## Entry contract Every entry has these fields: - `code`: an opaque identifier in the form `MN0001`. The number does not encode the diagnostic category, object, severity, or implementation order. - `slug`: a unique lowercase kebab-case name used by tools and people. - `status`: `defined` before the code is emitted, `active` once a supported surface emits it, `deprecated` after it has a replacement, or `retired` after the diagnostic is removed without a replacement. Retired entries remain cataloged permanently but cannot be emitted. - `category`: the kind of contract involved: `configuration`, `communication`, `dom`, `lifecycle`, or `ownership`. - `severity`: `error`, `warning`, or `info`, following the model below. - `objects`: the public Marionette objects involved in the invariant. - `remediation`: concise guidance for correcting the violation. This is human prose and may improve without changing the diagnostic identity. - `docsAnchor`: the permanent version-neutral documentation route. It is always `/errors//`. - `surfaces`: the places that report the diagnostic, or historically reported it for a retired entry: `runtime`, `lint`, `development`, `test`, or `benchmark`. - `benchmarkCategory`: the public benchmark category used to classify the violation. A deprecated entry also has `replacementCode`, which must identify another catalog entry. Defined, active, and retired entries cannot declare a replacement. ### Severity model - `error` means the invariant is violated and the requested operation cannot safely continue. Runtime surfaces throw; lint and validation surfaces fail their check; benchmark runs count the violation as incorrect. - `warning` means execution can continue but the usage is unsafe, deprecated, or likely unintended. Tools report it without changing runtime control flow; release evidence must explicitly approve or eliminate it. - `info` records deterministic context or guidance without indicating incorrect behavior. It does not fail an operation, check, or benchmark result by itself. For a retired entry, the stored severity and surfaces retain the diagnostic's historical classification. The generated reference labels those values as historical for display only. The `retired` status is authoritative: the entry is not a current error, warning, informational report, or supported-surface mapping. ## Stability policy Codes and slugs are unique and are never reassigned. The numeric portion of a code is allocated monotonically, gaps are allowed, and entries are never renumbered to close a gap. Deprecation retains both the catalog entry and its `/errors//` route and names the replacement. Retirement retains the identity and route without implying a replacement. Deletion and reuse are not supported. Before stable v5, defined catalog fields may be revised through reviewed changes. After stable v5, active, deprecated, and retired entries follow these rules: - adding a diagnostic or deprecating one is a minor change; - retiring an active diagnostic changes supported behavior and requires major-version review; - clarifying remediation without changing its meaning is a patch change; - changing the meaning of a machine-readable field or the schema is a breaking change and requires a new schema version and major-version review; - deleting or reusing a published code, slug, or diagnostic route is prohibited. Messages are deliberately not catalog identifiers. Human-readable runtime messages may improve while the code and slug remain stable. ## Surface mappings Runtime diagnostics declare their catalog identifier as a literal `code` property. Custom ESLint rules under `eslint-rules/` default-export an object literal whose `meta` object declares exactly one literal `diagnosticCode`. Benchmark and test results record the same code rather than copying the diagnostic meaning into a second identifier. Runtime diagnostic options and lint-rule metadata cannot use computed keys, spreads, or duplicate mapping properties. This keeps the emitted code statically decidable. A `defined` entry must move to `active` in the same change that first emits it. A retired entry cannot be emitted or mapped by a supported surface. `npm run check:diagnostics` derives the shipped source graph from the production Rollup inputs, rejects runtime codes or lint-rule mappings that are not in the catalog, and rejects a lint rule without a mapping. Documentation routes are generated from the catalog and then checked by `npm run docs:check`; they are not maintained as a second hand-written list. ## Initial scope The initial active entries describe only deliberate errors already thrown by the framework. Retired entries reserve identities that were formerly active; they do not reserve codes for planned validation. Defined entries likewise are not placeholders for incidental JavaScript exceptions or benchmark hypotheses. New invariants receive codes when their behavior and remediation are implemented and reviewed. The generated [diagnostic reference](/errors/index.md) lists the current catalog directly from the machine-readable source. A shared invariant has one code even when more than one framework object reports it. ## Argument types and runtime diagnostics Marionette trusts the declared shapes of callbacks, arrays, View instances, configuration objects, and adapter methods. TypeScript consumers receive errors for unsupported shapes during type checking. JavaScript consumers follow the same documented contracts; unsupported arguments have no guaranteed runtime diagnostic. Runtime diagnostics remain for ownership conflicts, invalid collection identity, missing DOM targets, unresolved handler names, and incompatible data sources. Retired shape-diagnostic codes remain listed for historical reference and are not reused. See [contributing](https://github.com/marionettejs/marionette/blob/b06750c507494441f0b2298766b70087e45346a2/CONTRIBUTING.md#runtime-checks-and-types) for the rule used when adding or removing checks. [Canonical source](/docs/markdown/docs/diagnostic-catalog.md) · [Source identity](/docs/manifest.json) --- Document: docs/public-api.md Canonical URL: https://marionettejs.com/docs/public-api/ Markdown URL: https://marionettejs.com/docs/public-api.md Reading SHA-256: 7fc7fc3446f2c9951c47055c524f4520e5d205ba87e4764b52c022d8eebd64ee # Public API index Use this index to identify the supported import and follow its behavior contract. The `marionette` package has named exports; it has no default export. Import optional integrations from their documented package subpaths, never from `src/` or generated internal files. ## Core runtime exports | Export | Purpose and reference | | --- | --- | | `View` | [Render and own one part of the interface](/docs/view.md). | | `CollectionView` | [Own ordered child Views](/docs/collection-view.md). | | `Region` | [Show, replace, detach, or destroy a current View](/docs/region.md). | | `Application` | [Coordinate asynchronous feature lifecycle and child Applications](/docs/application.md). | | `Behavior` | [Share host View interactions and lifecycle](/docs/behavior.md). | | `MnObject` | [Own nonvisual events, State, and synchronous cleanup](/docs/mn-object.md). | | `Events` | [Compose the event/listening contract](/docs/events.md#events-api). | | `Radio` | [Use the default runtime's named message channels](/docs/radio.md). | | `DataApi`, `setDataApi` | [Read and observe the selected data source](/docs/data-api.md). | | `StateApi`, `setStateApi` | [Observe State and dispose owned sources](/docs/state.md). | | `DomApi`, `setDomApi` | [Create, query, attach, and update DOM](/docs/dom-api.md). | | `setRenderer` | [Configure synchronous template evaluation](/docs/rendering.md#using-a-custom-renderer). | | `setEventDelegator` | [Configure DOM event registration and cleanup](/docs/dom-interactions.md#eventdelegator-adapter). | | `createMarionette` | [Create independent classes, configuration, and Radio](/docs/runtime-isolation.md). | | `monitorViewEvents` | [Bridge lifecycle notifications for supported custom Views](#monitorvieweventsview). | | `extend` | [Extend a function constructor](/docs/utils.md#extend). | | `MarionetteError` | [Inspect a framework invariant failure](/docs/diagnostics.md). | | `VERSION` | [Read the package version](/docs/utils.md#version). | [Configuration method contracts](/docs/runtime-isolation.md#configuration-method-contract) identify which classes each setter affects, its return value, and its scope. Choosing one provider does not configure the other providers. ## `monitorViewEvents(view)` This synchronous helper installs lifecycle listeners on a supported custom View and returns `undefined`. It propagates attachment and detachment notifications to managed children and derives `dom:refresh`/`dom:remove` from render and attachment state. Repeating the call does not install duplicate monitoring; `monitorViewEvents: false` skips installation. Marionette Views are monitored automatically. This helper is for integrations that implement the [supported View lifecycle](/docs/region.md#wrapping-a-non-marionette-view), including event methods and managed-child access. It is not a MutationObserver: appending arbitrary DOM does not notify it. Prefer a Marionette wrapper View for third-party widgets so ownership and cleanup remain explicit. ## Companion packages | Import | Public surface | Reference | | --- | --- | --- | | `@mnjs/data` | `Model`, `Collection`, `DataApi`, `StateApi`, `triggerMethod` | [Native observable data](/docs/data-package.md) | | `@mnjs/radio` | `Radio`, `createRadio`, `Channel`, `Requests` | [Standalone Radio](/docs/radio-package.md) | | `@mnjs/utils` | Shared events, bindings, option, inheritance, and event-building helpers | [Utility exports](/docs/utils-package.md) | | `@mnjs/adapters/backbone` | Default Backbone data/State adapter | [Backbone integration](/docs/backbone.md) | | `@mnjs/adapters/xstate` | Default `createXStateActorApi` factory | [XState integration](/docs/data-api.md#xstate-actors) | | `@mnjs/adapters/dom/jquery` | Default jQuery DomApi | [jQuery DOM](/docs/dom-api.md#optional-jquery-adapter) | | `@mnjs/adapters/dom/morphdom` | Default Morphdom DomApi | [DOM update adapters](/docs/rendering.md#rendering-to-dom) | | `@mnjs/adapters/dom/lit-html` | Default Lit DomApi | [DOM update adapters](/docs/rendering.md#rendering-to-dom) | Add a companion package as a direct dependency when application code imports it. Match Marionette package versions during prereleases. Optional integrations need only their selected peers; see [Choosing integrations](/docs/choosing-integrations.md). ## TypeScript exports Core also exports types for class instances and constructors, class configuration, Region definitions and show options, Application readiness context, DOM events and triggers, UI bindings, Behavior definitions, event and request contracts, and provider contracts (`DataApiContract`, `DomApiContract`, `StateApiContract`, `EventDelegator`, and `Renderer`). Use `import type` for these names. They do not create runtime values or install a provider. The package's declarations are the exact signature reference. Keep inferred subclass types when possible rather than annotating an extended View as the broad base instance type and losing its application-specific methods. [Canonical source](/docs/markdown/docs/public-api.md) · [Source identity](/docs/manifest.json) --- Document: packages/radio/readme.md Canonical URL: https://marionettejs.com/docs/radio-package/ Markdown URL: https://marionettejs.com/docs/radio-package.md Reading SHA-256: a0461bec43fb673ce109ae5d1902a78aeb8eb011ef53f00a1eb4a7121a261bb7 # @mnjs/radio Named channels for events and request/reply, usable without Marionette core or a DOM. ```sh npm install @mnjs/radio@5.0.0-beta.1 ``` ```js import { Radio, createRadio } from '@mnjs/radio'; const channel = Radio.channel('app'); channel.reply('title', () => 'Hello'); channel.on('refresh', () => console.log('Refreshing')); channel.request('title'); channel.trigger('refresh'); const isolatedRadio = createRadio(); ``` `Radio` is the default instance also exported by `marionette`. Within the same module format and package installation, either import reaches the same channels. `createRadio()` creates an independent channel registry. Each `createMarionette()` runtime also owns its own Radio instance; use that runtime's `Radio` when binding its objects and applications. The package depends on `@mnjs/utils`, which supplies Events and shared helpers. It does not depend on core. ESM and CommonJS exports include `Radio`, `createRadio`, `Channel`, `Requests`, and their public types. ESM and CommonJS each have their own default instance; do not mix the two formats to share a channel registry. Radio, utils, data, adapters, and core are versioned and released together. ## Standalone messaging ```js import { Channel, Requests } from '@mnjs/radio'; const local = new Channel('editor'); local.on('save', () => console.log('Saved')); local.reply('title', 'Untitled'); const service = Object.assign({}, Requests); service.reply('ready', true); ``` `new Channel(name)` creates an independent Events-and-Requests object. It is not registered with Radio; call its `reset()` to remove its handlers and owned listeners. Two standalone channels with the same name are still separate objects. `Radio.reset()` only covers channels obtained through `Radio.channel(name)`. The named `Channel` export is `Radio.Channel`. Use `new isolatedRadio.Channel(name)` when a standalone channel should share a particular Radio instance's logging configuration. `Requests` adds only request/reply methods to its receiver; it uses the default Radio's warning configuration. ## Logging Assign `radio.log(channelName, eventName, ...args)` to receive activity from `tuneIn()`, and `radio.debugLog(warning, eventName, channelName)` to receive diagnostics. The defaults write to the console. ```js const radio = createRadio(); radio.log = (channel, event, ...args) => console.log({ channel, event, args }); radio.debugLog = (warning, event, channel) => console.warn({ warning, event, channel }); radio.setDebug(); radio.tuneIn('app'); ``` Each Radio instance owns its hooks. They run with that Radio as `this`, and existing channels use the current hook, even when it is replaced after `tuneIn()`. `setDebug(false)` suppresses warning delivery to custom hooks too. Standalone channels use their constructor's Radio configuration; the shared default Requests mixin uses the default Radio. Hook exceptions propagate to the caller. [Canonical source](/docs/markdown/packages/radio/readme.md) · [Source identity](/docs/manifest.json) --- Document: packages/utils/readme.md Canonical URL: https://marionettejs.com/docs/utils-package/ Markdown URL: https://marionettejs.com/docs/utils-package.md Reading SHA-256: 1c4030cc3fe442d93b97e44c5aab30341dc08ac3d02308185b5aba2ce7b56901 # @mnjs/utils The small helpers behind Marionette, available for your own components. Marionette and `@mnjs/data` import these same implementations. ```bash npm install @mnjs/utils@5.0.0-beta.1 ``` Use the same version for all Marionette packages. Core and data install utils automatically as a regular dependency. Add it directly when your application imports it. ## Building a component Methods such as `getOption`, `normalizeMethods`, and `triggerMethod` use their receiver as the component. Mix them into a prototype or call them with `.call()`. ```js import { Events, getOption, normalizeMethods, triggerMethod } from '@mnjs/utils'; const component = { ...Events, getOption, normalizeMethods, triggerMethod, options: { label: 'Inbox' }, onOpen() { return this.getOption('label'); } }; component.triggerMethod('open'); // 'Inbox' component.normalizeMethods({ open: 'onOpen' }); ``` ## Events `Events` is the shared event implementation used by Marionette, Radio, and native data. Mix it into an object with `Object.assign({}, Events)` to use `on`, `off`, `trigger`, `listenTo`, and `stopListening` without core. ## Helpers Use object spread or `Object.assign` for ordinary copying and composition. Inherited enumerable parent statics are copied only inside `extend`. - `getValue(object, key, fallback)` reads a value and calls it on the object if it is a function. `getOption` reads from `this.options`, then the receiver. - `mergeOptions(options, keys)` copies selected options onto the receiver. - `normalizeMethods(map)` resolves method names on the receiver. `resolveMethod(context, method, name)` resolves one handler. - `bindEvents` and `unbindEvents` use the receiver's listening methods. `bindRequests` and `unbindRequests` register or remove channel replies with the receiver as their context. `normalizeBindings(context, map)` resolves an event map without subscribing. - `triggerMethod(eventName, ...args)` invokes the matching `onEventName` method and triggers the event. - `extend` is the function-constructor inheritance helper used by Marionette. - `MarionetteError` is the same error constructor exported by Marionette. - `isString` recognizes primitive and boxed strings. `setProperty` assigns a property, treating `__proto__` as an own data property. ES modules, CommonJS, and TypeScript declarations are included. The package has no runtime dependencies and declares no side effects. Bundlers can retain only the imported helpers. Marionette's standalone UMD bundles include these helpers; module consumers share the installed package. Event-building helpers `buildEventArgs`, `eventSplitter`, `callHandler`, and `onceWrap`, plus `uniqueId`, are shared by core and Radio. [Canonical source](/docs/markdown/packages/utils/readme.md) · [Source identity](/docs/manifest.json) --- Document: docs/migration-from-v4.md Canonical URL: https://marionettejs.com/docs/migration-from-v4/ Markdown URL: https://marionettejs.com/docs/migration-from-v4.md Reading SHA-256: 7d62a1d35855c2e2889c479c6cafcd4c0909cc1d8a95d41547da1239e69aaede # Marionette v4 to v5 Compatibility Ledger This ledger records the public compatibility boundary between Marionette v4 and v5. It is a reference, not the full procedural upgrade guide. Detailed upgrade steps that are not already documented are tracked in [the stable-release documentation issue](https://github.com/marionettejs/marionette/issues/147). Status values describe the v5 outcome: - **Preserved**: the supported public behavior remains available. - **Changed**: the public behavior remains relevant but has a different contract. - **Removed**: the v4 behavior is not supported in v5. - **Added**: v5 provides a new public capability with no core v4 equivalent. - **Optional**: the behavior is available only through an explicit opt-in. - **Renamed**: the capability remains under a different name. - **Documented**: the public extension point is retained and called out here. If your application imports directly from @mnjs/radio, declare version 5.0.0-beta.1 as a direct dependency in your application package.json. Do not rely on Marionette’s transitive dependency. ## Compatibility ledger | Area | v4 behavior | v5 behavior | Status | Migration note | | --- | --- | --- | --- | --- | | Package name | Installed as `backbone.marionette`. | Published as `marionette`. | Changed | Replace the package name. See [Installing Marionette](/docs/installation.md#install). | | Install command | `npm install backbone.marionette` installed Marionette under the v4 name. | Install core with `npm install marionette@5.0.0-beta.1`; add optional peers only when used. | Changed | See [peer dependencies](/docs/installation.md#peer-dependencies). | | Default export namespace | Namespace-style default import usage was supported. | A default namespace export is not supported. | Removed | Use named imports. See [Quick start](/docs/installation.md#quick-start); final migration guidance is tracked in [#147](https://github.com/marionettejs/marionette/issues/147). | | Named exports | Classes and utilities were available as named exports. | Named exports are the supported module API. | Preserved | Import only what is needed, for example `import { View, Region } from 'marionette';`. | | Feature flags | `setEnabled` and `isEnabled` configured one module-global registry, including `childViewEventPrefix`, `triggersPreventDefault`, `triggersStopPropagation`, `DEV_MODE`, and application-owned names. | The registry and both named exports are removed. Child event prefixes remain configurable per View. Trigger default prevention and propagation remain configurable per trigger. | Removed | Remove flag calls and imports. The disabled `triggersPreventDefault` and `triggersStopPropagation` flags globally inverted trigger defaults and have no global replacement; set `preventDefault: false` or `stopPropagation: false` on each affected trigger. Set `childViewEventPrefix` on the owning View, and move application-owned values to Application State or explicit application configuration. Future deprecations use cataloged diagnostics instead of `DEV_MODE`. | | Backbone dependency | Backbone was a required runtime dependency and supplied core model, collection, event, and view behavior. | Marionette core does not import Backbone. Plain objects and arrays use the neutral DataApi; Backbone is an explicit integration. | Optional | Install `@mnjs/adapters` and configure its `BackboneApi` with `setDataApi()` for model/collection use and `setStateApi()` separately for Backbone state observation. See [Optional Backbone](/docs/backbone.md). | | Model and collection data | Core read Backbone-specific `cid`, `attributes`, `get`, `models`, `indexOf`, and structural event payloads directly. | Core reads identity, values, serialization, ordered model snapshots, subscriptions, and structural changes through DataApi. | Changed | Use plain objects and arrays with the default adapter, configure `BackboneApi` for Backbone, or configure a custom adapter with `setDataApi`. See [Data API](/docs/data-api.md). | | Serialized collection template property | A View with a collection and no model supplied the result of `serializeCollection()` to the template as `items`. | The template receives that result as `models`, matching the DataApi vocabulary while remaining distinct from the raw ordered snapshot returned by `DataApi.models(collection)`. Default serialization returns an array of serialized values; an override may return another shape. The pre-stable `items` property is removed. | Changed | Replace collection-template reads and destructuring of `items` with `models`; do not retain a fallback for both names. | | Region display input | `Region#show` and `View#showChildView` accepted a View instance, template function, string, or View-options object. Non-View values implicitly constructed a base Marionette View. | Both methods require a Marionette View instance. The public types require an instance; Regions do not allocate hidden Views or provide a custom diagnostic for unsupported input shapes. | Changed | Construct the intended View explicitly and pass the instance. Replace strings or template functions with `new View({ template: () => content })`, and wrap former View-options objects with `new View(options)`. | | Local state | Core did not provide a first-class state-source composition contract; applications commonly used a Backbone model or separate mixin. Toolkit mixed Backbone-backed `getState(attr)`, `setState`, `toggleState`, `hasState`, and reset helpers into several owners. | `Application`, `MnObject`, `View`, `CollectionView`, and `Behavior` compose an exact source through borrowed `state` or owned `createState(options)`. `getState()` returns that source, and StateApi observes `stateEvents`. The v5 alpha concrete `State` export is removed. | Changed | For simple local values, return a plain object from [`createState()`](/docs/state.md) and use property access. For reactive state, supply the provider's source and configure its StateApi. Move mutation to the source's native API; core adds no universal mutation wrappers. | | Explicit Backbone integration | Backbone integration was applied as part of the v4 dependency relationship. | `@mnjs/adapters/backbone` provides one combined DataApi and StateApi adapter without modifying Backbone objects, prototypes, or native event behavior. | Optional | Pass `BackboneApi` to the selected runtime's `setDataApi()` and `setStateApi()` methods before constructing Marionette owners that consume those sources. See [Optional Backbone](/docs/backbone.md). | | jQuery dependency | jQuery commonly backed Backbone view and Marionette DOM behavior. | Marionette core does not import jQuery. | Optional | Install jQuery only when using `@mnjs/adapters/dom/jquery`. See [jQuery DOM adapter is optional](/docs/installation.md#jquery-dom-adapter-is-optional). | | Optional jQuery DomApi | jQuery-backed DOM operations were part of the common v4 stack. | The `@mnjs/adapters/dom/jquery` subpath provides explicitly selected jQuery-backed DOM methods without adding `$el` to core. | Optional | Configure it at app boot with `setDomApi`. See [jQuery DOM compatibility](/docs/upgrade-guide.md#jquery-dom-compatibility). | | `$el` | Views and Behaviors exposed a jQuery wrapper. | Core and adapters do not create `$el`; Views keep a fixed root. | Changed | Assign `this.$el = $(this.el)` in the View, CollectionView, or Behavior `initialize()` when needed. See [jQuery DOM compatibility](/docs/upgrade-guide.md#jquery-dom-compatibility). | | `view.$(selector)` | Returned a jQuery collection in the common Backbone/jQuery configuration. | Delegates to `DomApi.findEl`, which returns a native `NodeList` by default or a jQuery collection with the optional adapter. | Changed | Prefer native collection APIs, or opt into `@mnjs/adapters/dom/jquery`. See [jQuery DOM compatibility](/docs/upgrade-guide.md#jquery-dom-compatibility). | | CollectionView `attachHtml` container | The second override argument was a jQuery-wrapped `$container`. | The second argument is the native child container element, equal to the CollectionView's `el` unless `childViewContainer` selects another element. | Changed | Update overrides to accept `attachHtml(els, container)` and pass the native `container` to DomApi operations. Do not depend on jQuery collection methods or restore a dual-shape argument. | | Region element resolution | Construction resolved selector strings through public `Region#getEl` before `initialize`; `getEl` returned a jQuery collection, and custom DomApi adapters could implement `getEl(selector)`. | Construction preserves the configured selector for `initialize` and defers public `Region#getEl` dispatch until the first DOM operation. `Region#getEl` returns the first matching native DOM element. `DomApi#getEl` is removed; selector lookup delegates to `findEl(context, selector)`. | Changed | Do not rely on constructor-time DOM lookup or `getEl` side effects. Make Region `getEl` overrides return one native DOM element. Replace DomApi `getEl` overrides with `findEl`, returning an array-like collection whose first entry is the matched element. | | Region `el` input | Accepted a selector string, DOM element, or jQuery-wrapped element. | Selector-string and DOM-element support are preserved. A jQuery collection is rejected even when the optional DomApi adapter is selected. | Changed | Pass the native element, such as `wrappedElement[0]`. Region remains the Marionette mount-point abstraction. See [View `el` is element-only](/docs/upgrade-guide.md#view-el-is-element-only). | | View `el` | Selector strings and jQuery-wrapped elements commonly worked through Backbone and jQuery. | `View` accepts a DOM element only and throws a migration hint for strings or wrappers. | Changed | Resolve a selector with `document.querySelector(...)` or unwrap a jQuery collection with `[0]`. See [View `el` is element-only](/docs/upgrade-guide.md#view-el-is-element-only). | | View root replacement | `setElement()` transferred a View to another element. | View and CollectionView roots are fixed at construction; `setElement()` is removed and the public instance `el` is readonly. | Removed | Supply `el` at construction. For a different root, destroy the old View and construct a new owner. See [View roots are fixed at construction](/docs/upgrade-guide.md#view-roots-are-fixed-at-construction). | | View DOM attributes | View attribute cloning could copy inherited enumerable properties. Attributes were applied through jQuery. | Attribute maps contribute own enumerable string keys and use DOM attribute names. `renderAttributes()` refreshes root attributes without rendering content. Only explicit `null` removes an attribute; undefined and omitted entries leave it untouched. Other values use native string conversion. | Changed | Use own attribute declarations and `null` for removal. For boolean HTML attributes use `disabled: isDisabled ? '' : null`; `false` becomes the string `"false"`. Set live form properties explicitly. Keep using the View-level `className` option; inside `attributes`, use `class` and `for`. | | CollectionView `emptyView` | Direct falsy values and resolvers returning `undefined`, `null`, or `false` disabled the empty view; other invalid definitions were skipped silently or failed with incidental errors. | Omitted values, direct `undefined`, `null`, or `false`, and resolvers returning those values disable the empty view. The public types describe these alternatives; no custom shape diagnostic is emitted. | Preserved | Existing conditional resolvers require no migration; return a View class or a supported disabled value. | | Detach semantics | jQuery detach operations preserved jQuery listener and data bookkeeping for detached nodes. | The native DomApi removes nodes without cleaning their listeners or jQuery data; the optional adapter delegates to jQuery detach operations. Referenced nodes retain their handlers and data in either case. | Changed | Choose the optional jQuery adapter for its documented query and content-operation semantics, not merely to retain referenced nodes during detach. See [`detachContents` policy](/docs/upgrade-guide.md#detachcontents-policy). | | Radio singleton | Applications commonly consumed the separate `backbone.radio` package, which also backed Marionette's `channelName`, `radioEvents`, and `radioRequests` integration. | Marionette exports its own built-in `Radio` singleton. It does not share channels with `backbone.radio`. | Changed | Replace every `backbone.radio` import together with the Marionette upgrade, including publishers and requesters outside Marionette classes. A mixed migration silently creates two disconnected buses. Do not bridge or mirror them. See [Atomic Radio migration](/docs/upgrade-guide.md#atomic-radio-migration). | | Multiple Marionette configurations | Root imports and mutable class configuration were effectively process-scoped. | Root imports still form one default runtime. Optional `createMarionette()` calls create isolated runtimes with their own runtime classes, adapters, renderer configuration, and Radio registries. | Added | Keep ordinary root imports unless isolation is required. When using `createMarionette()`, construct Regions and child Applications from the selected runtime. See [Runtime isolation](/docs/runtime-isolation.md). | | Radio debug configuration | `Radio.DEBUG = true` enabled Backbone.Radio diagnostics. | Use `Radio.setDebug()` and `Radio.setDebug(false)`. The `DEBUG` property is not supported. | Changed | Replace assignments with the explicit method during the atomic Radio migration. | | Radio request mixin | Backbone.Radio exposed `Radio.Requests` for direct mixin use. | `Requests` is a named export from `@mnjs/radio`; request/reply methods remain on channels and the top-level Radio API. | Changed | Import `Requests` from the Radio package and compose it with `Object.assign({}, Requests)`. | | Radio diagnostic override hooks | Backbone.Radio exposed `Radio.log` and `Radio.debugLog`. | Both hooks are replaceable on each Radio instance; `setDebug` gates custom warning hooks. | Changed | Assign hooks on the Radio instance your channels use. Hooks receive that Radio as `this` and replacements apply to existing channels. | | Radio Channel construction and registry | Backbone.Radio exposed its Channel constructor and registry. | `Channel` and `Requests` are named exports from `@mnjs/radio`; each Radio also exposes its Channel constructor. The registry remains private. | Changed | Use `Radio.channel(name)` for shared channels or `new Channel(name)` for independent channels. Standalone owners call `reset()` themselves. | | Radio method receiver | Backbone.Radio top-level methods read their channel factory and registry from `this`, so borrowed methods could target an alternate receiver. | Top-level methods dispatch through the Radio instance that created them. | Changed | Use `createRadio()` for another registry. Borrowing a method does not create or select another Radio instance. | | Radio named reset | Resetting an unknown channel could fail with an incidental `TypeError`, and names matching inherited object properties could resolve incorrectly. | `Radio.reset(name)` throws `MN0021` for an unknown channel, while explicitly created channel names are registry-owned. | Changed | Create the channel before resetting it, or call `Radio.reset()` with no arguments to reset all existing channels. | | Request-name ownership | Inherited request-registry properties could be mistaken for named handlers or the `default` fallback. A `__proto__` request name could change the registry or result-map prototype instead of becoming an own entry. Flattening a nested multi-request result could copy inherited enumerable properties. | Only explicitly registered own handlers are invoked or reported as overwritten. Request result maps use safe own string properties, including for `__proto__`, and nested results contribute own enumerable string properties only. | Changed | Register every named and default handler explicitly; do not depend on request-registry prototype inheritance, and move intended nested result values onto the result object itself. | | UMD global | Script builds exposed the `Marionette` global. | Unminified and minified UMD compatibility builds remain supported throughout v5 for no-bundler, AMD, and `Marionette`-global consumers. | Preserved | Existing direct-script integrations can retain the global while updating changed APIs. New applications should use the canonical ESM entry. | | CJS entry | CommonJS consumers could require Marionette. | `require('marionette')` resolves to the CJS compatibility build and returns named API properties throughout v5. | Preserved | Legacy Node and build-tool consumers can destructure the required API instead of expecting a restored default namespace contract. New applications should use ESM. | | ESM entry | ES module named imports were supported. | `import` resolves to the ESM build and named imports remain supported. ESM is the canonical distribution for new applications. | Preserved | Use named imports from `marionette`. | | Underscore dependency | Marionette required Underscore through its package dependency relationship. | Marionette core does not import or declare Underscore as a peer dependency. | Removed | Remove Underscore if it was installed only for Marionette; keep it when application code uses it directly. Backbone manages its own dependency. See [Underscore is no longer a peer dependency](/docs/upgrade-guide.md#underscore-is-no-longer-a-peer-dependency). | | Client ID sequence ownership | Marionette constructors and event-listener bookkeeping drew IDs from Underscore's counter, so external Underscore calls could affect later Marionette numeric suffixes. | One loaded copy of Marionette owns one sequence shared by its constructors and event-listener bookkeeping. Complete Marionette-generated IDs remain unique when types reuse a custom prefix, but the sequence is not coordinated with Underscore or Backbone. | Changed | Treat `cid` values as opaque stable instance identifiers. Do not parse or compare numeric suffixes, depend on allocation order, or coordinate IDs through `_.uniqueId`. | | Class extension input inheritance | Inherited enumerable properties on the `staticProps` hash passed to `extend` could become child-constructor properties. | The public `protoProps` and `staticProps` hashes contribute own enumerable string and symbol keys. Inherited enumerable statics from the parent constructor remain available on the child. | Changed | Move intended prototype and static definitions onto the corresponding input hash itself; do not inherit configuration into either hash. | | Instance option and render-data inheritance | Underscore-backed shallow merges could copy inherited enumerable properties when combining constructor options and resolved defaults, Region definitions and defaults, `childViewOptions`, or serialized data and `templateContext`. `mergeOptions` could also read inherited or non-enumerable named properties. | Constructor/default options, Region options, and child View options use own enumerable string and symbol properties and safely preserve a literal own `__proto__` property. `mergeOptions` copies only requested own enumerable string properties. Serialized data and `templateContext` use own enumerable string and symbol properties when both are combined; a one-sided fast path still returns the original object unchanged. | Changed | Move intended merged values onto the supplied object itself; do not use prototype inheritance or non-enumerable properties for these inputs. | | Target-first root utilities | The package root exported `bindEvents`, `unbindEvents`, `bindRequests`, `unbindRequests`, `mergeOptions`, `getOption`, `normalizeMethods`, and `triggerMethod` wrappers that accepted any compatible target object as their first argument. | These conventions have one canonical form as methods on Marionette instances. The root exports, their internal proxy helper, and the public adapter for applying them to arbitrary plain objects are removed. | Removed | Call the corresponding instance method, such as `owner.normalizeMethods(bindings)` or `owner.bindEvents(entity, bindings)`. When a plain object needs similar behavior, extend `MnObject` or own that local adapter explicitly rather than borrowing a Marionette prototype method. | | `mergeOptions` key collection | Underscore's iterator accepted strings, `arguments`, generic array-like objects, and ordinary object values as requested option names. Invalid or missing key collections were silently ignored. | `mergeOptions(options, keys)` requires `keys` to be an Array when options are present; the declared contract replaces custom shape validation. | Changed | Pass the requested option names as an Array. | | Private immediate-child traversal | The private `_getImmediateChildren()` result was passed to Underscore's generic iterator, which also traversed arbitrary keyed objects. | Marionette-owned implementations return Arrays. The private type requires an Array; traversal trusts that contract. | Changed | Do not override private `_getImmediateChildren()`. Use documented View, Region, and CollectionView APIs to own child Views. | | View constructor option precedence | `View` and `CollectionView` passed options to `preinitialize`, then Backbone assigned the public `model`, `collection`, `el`, `id`, `attributes`, `className`, `tagName`, and `events` options before creating the element. Supplied options therefore won conflicts with assignments made by the hook. | The hook can observe the supplied options before the same public constructor options are reapplied. Conflicting supplied options remain authoritative, while v5's private initialization order is unchanged. | Preserved | Use `preinitialize` to derive early state from constructor options. Use `initialize` when an intentional replacement must occur after final public option assignment and element setup. | | View `preinitialize` and internal setup order | Before Backbone invoked the host's `preinitialize` hook, `View` installed lifecycle monitoring and constructed Behaviors and Regions; `CollectionView` installed monitoring and constructed its child storage and Behaviors. | The standalone host constructor invokes `preinitialize` before that internal setup. Behavior `initialize` can therefore read host state established by the hook, while the hook cannot depend on constructed Behaviors, Regions, child storage, or lifecycle monitoring. | Changed | Keep early host state derivation in `preinitialize`. Move code that needs Marionette-owned collaborators or lifecycle dispatch to the host's `initialize` method. | | CollectionView empty Region initialization | The constructor invoked the host's `initialize` before calling overridable `getEmptyRegion()` to establish the default empty-view Region. | The same order is preserved. An override can depend on state established by `initialize`; calling `getEmptyRegion()` from `initialize` remains safe because the later constructor call reuses that Region. | Preserved | Keep empty-Region override setup in `initialize` or `getEmptyRegion`; no migration is required. | | Destruction during View initialization | A `View` or `CollectionView` destroyed from its own `initialize` continued the constructor tail, rebinding entity events and firing Behavior `initialize` after Behavior destruction. `CollectionView` also replaced its destroyed empty Region with a live one. | Destruction is terminal. After `initialize` returns, a destroying or destroyed host skips remaining constructor setup; a destroyed CollectionView retains its destroyed empty Region. | Changed | Initialization code may destroy a host without adding guards for later constructor setup. Do not expect entity events, Behavior initialization hooks, or a live empty Region after that destruction. | | Child View collection helpers | `CollectionView#children` proxied Underscore collection methods, including iteratee shorthand, a private-array callback argument, Underscore return values, deep/function-form `invoke`, array-form deep paths in `pluck`, and count coercion. | The 19 documented helpers are owned by Marionette. Callback methods require functions and expose only View and index; `each` returns the child container; `reduce` follows native initial-value rules; `invoke` accepts a direct string method; `pluck` reads one direct View property; positional counts are nonnegative integers. Callback and method shapes are checked by the public types. Invalid counts and an empty reduction without an initial value still throw `MN0024`. | Changed | Replace `map('id')` with `map(view => view.id)` or `pluck('id')`. Replace `pluck(['model', 'cid'])` with `map(view => view.model?.cid)`. Do not use the callback's former third argument or depend on `each` returning an array. Replace deep/function-form `invoke` with an explicit callback, and pass valid integer counts. | | Child View collection aliases and iteration | Undocumented Underscore aliases such as `forEach`, `detect`, `select`, `all`, `any`, and `include` were available through the proxy. The child container was not natively iterable. | The aliases are removed. The canonical methods remain, and the child container supports `for...of`, spread, destructuring, and `Array.from`. | Changed | Replace the aliases with `each`, `find`, `filter`, `every`, `some`, and `contains`, respectively. Prefer native iteration when no collection-helper return value is needed. | | Child View identity and ownership | Plain-object cid indexes could mistake inherited property names for children, and `removeChildView` or `detachChildView` could mutate a supplied View that was not actually owned by the CollectionView. | View cids remain Marionette-owned keys. Model identity comes from `DataApi.key()` and is stored in a `Map`; `findByModelCid` is removed while `findByModel` uses the configured adapter. Membership requires the exact View instance. | Changed | Replace `findByModelCid(cid)` with `findByModel(model)`. Configure stable source identity through DataApi rather than adding `cid` to otherwise neutral application data. | | CollectionView filter iteration | Underscore supplied CollectionView child iteration and predicate-object matching, including accepting arrays as predicate objects. | Function filters run with the CollectionView as their receiver and receive `(childView, index, liveChildArray)` while traversing the initial length densely. Predicate maps snapshot own enumerable string keys and values per pass, require present strictly equal model attributes, and exclude inherited, symbol, and non-enumerable keys. Arrays are not predicate maps. | Changed | Use a function filter for custom matching or mutation-sensitive logic. Supply predicate shorthand as an ordinary object and use the same object reference for nested attribute values that should match. | | CollectionView removal-only updates | Every collection update flowed through sort, filter, and child rendering, so removing one model could move every surviving child through a document fragment even when default collection ordering or disabled ordering already preserved their relative order. | A removal-only update on an already-rendered, unfiltered CollectionView with default collection ordering or ordering disabled destroys the removed child without moving or rerendering synchronized visible survivors when the default sort, filter, and comparator-query methods are used. Empty-view, deferred-child, custom filter or comparator, overridden query methods, add, and merge cases retain the full update path. | Changed | Observe `remove:child` for removals. Do not rely on sort or `render:children` firing when no surviving child needs sorting, rendering, or placement. Private `_viewComparator` and `_onCollectionUpdate` overrides are not supported extension points; use the documented public options and methods. | | Event bookkeeping rename | Backbone-compatible private event fields such as `_events`, `_listeningTo`, and `_listenId` could be observed. | Marionette's built-in Events implementation uses private `_rdEvents`, `_rdListeningTo`, `_rdListeners`, and `_rdListenId` fields. | Renamed | Do not read or write event bookkeeping fields; use `on`, `off`, `listenTo`, and `stopListening`. Procedural guidance is tracked in [#147](https://github.com/marionettejs/marionette/issues/147). | | Event aliases | Backbone.Events exposed `bind` as an alias of `on` and `unbind` as an alias of `off`, including on Radio channels. | Marionette Events and built-in Radio expose only the canonical `on` and `off` methods. The optional Backbone integration does not modify Backbone objects, so native Backbone instances retain `bind` and `unbind`. | Changed | Replace the aliases on Marionette objects and Radio channels. Existing Backbone-owned code may continue using Backbone's native aliases, though `on` and `off` remain preferred. | | Event and request override dispatch | `once` registered through overridable `on`; `listenToOnce` registered through overridable `listenTo`; and Backbone.Radio registered `replyOnce` through overridable `reply`. Map and space-separated reply operations dispatched each entry through their public method. | The same public override dispatch is preserved. Emitter interoperability calls the documented three-argument `on` and `off` methods once per binding, including when an override delegates with only those documented arguments. | Preserved | Lifecycle and instrumentation mixins may continue overriding the canonical registration methods. Overrides should delegate synchronously when they want the base registration behavior. | | Object-form event triggering | Backbone.Events treated map keys as event names, ignored the mapped values, and passed arguments after the map to each handler. | Object-form `trigger` is a Marionette extension: each map value is the sole argument for its event, and arguments after the map are not forwarded. | Changed | Move the intended per-event handler argument into each map value. Use separate string-form `trigger` calls when an event needs multiple arguments. | | Object-form requests | Backbone.Radio passed each mapped value as the first argument to its handler and forwarded arguments after the map. | Marionette preserves that argument order and returns the same per-name result map shape. | Preserved | No request-call change is required. | | Event-name ownership | Event names matching inherited object properties could fail during registration or consult inherited private-store entries. A literal `__proto__` name could affect the event store's prototype. | Only explicitly registered own event names are dispatched or removed. `constructor`, `toString`, `__proto__`, and other inherited names are ordinary event names, and `__proto__` does not change the store prototype. | Changed | Register and remove event names through `on`, `off`, `listenTo`, and `stopListening`; do not modify or inherit from private event stores. | | Entity-event map `__proto__` name | Declarative entity-event maps silently discarded an own enumerable `__proto__` name during normalization, so it was never bound or selectively unbound. | `bindEvents` and selective `unbindEvents`, including `modelEvents`, `collectionEvents`, and `radioEvents`, throw `MN0026` before delegation when the map has an own enumerable `__proto__` entry. Marionette does not reject other prototype-collision names: its Events API supports them, but third-party emitters such as Backbone may not safely support every name. | Changed | Rename the `__proto__` entity event or bind it through an entity API that explicitly supports the name; verify other prototype-collision names against the entity's emitter, and omit the map to unbind every event from an entity. | | `Mn.Object` | The default namespace exposed an `Object` alias for the Marionette object class. | The alias is not restored. | Removed | Use `import { MnObject } from 'marionette';`; final migration guidance is tracked in [#147](https://github.com/marionettejs/marionette/issues/147). | | `MnObject` | The Marionette object class was available as the named `MnObject` export. | `MnObject` remains a named export. | Preserved | Import it directly: `import { MnObject } from 'marionette';`. | | Reentrant destruction | Calling `destroy()` from `before:destroy` could recurse or repeat teardown for MnObject, Application, and Region. View guarded reentry, but a throwing `before:destroy` left it unable to retry. | MnObject, View, Behavior, and Region guard repeated synchronous teardown as documented by their class contracts. Application destruction is part of its asynchronous lifecycle: compatible repeated calls share an in-flight Promise, and later calls after destruction resolve `true` without restarting teardown. | Changed | Synchronous lifecycle errors stop teardown; later `destroy()` calls do not retry it. For Application, await `destroy()` and treat a rejected current hook as failure; ordinary supersession resolves rather than rejects. | | Application lifecycle | `Application#start(options)` synchronously fired `before:start` and `start` on every call and returned the Application. Application had no core stop, restart, readiness, running-state, or overlap contract. | `start`, `stop`, `restart`, and `destroy` return `Promise`. `true` means the requested target state settled, including idempotent no-op; `false` means a later incompatible operation superseded it. Current hook failures reject. `isRunning()` is true only after startup readiness. Readiness hooks receive an operation context whose `signal` is aborted when their phase is invalidated. | Changed | Await startup before route dispatch or other work that requires readiness. Move asynchronous preparation into a Promise returned by `onBeforeStart` and pass its context signal to cancellable work. Do not treat `false` as failure or add a catch for ordinary cancellation. Remove Toolkit-style `triggerStart` / `finallyStart` overrides; core awaits `onBeforeStart` directly. | | Application ownership and hierarchy | Core Application had no parent, named-child, root, or child lifecycle contract. Toolkit supplied a separate App class with class/config overloads and per-child lifecycle flags. | Application owns existing child Application instances through one explicit registration path. Name, individual-child, presence, and fresh-snapshot reads expose the public ownership contract without private-field access. Owned children start and stop sequentially with their owner. A conflicting direct child operation cancels owner completion, while descendant startup cannot interrupt owner destruction. Parent destruction stops children before its readiness hook, then destroys them in registration order. A child destroyed directly removes itself from its owner. Conflicts throw `MN0031`, while registration after either lifecycle becomes terminal is a no-op. | Added | Keep Toolkit's established `addChildApp`, `getChildApp(s)`, `removeChildApp`, and `getName` vocabulary, but construct the child explicitly and use `hasChildApp` when allocation must be avoided. Remove `AppClass` configs, `preventDestroy`, `*WithParent` flags, and public parent/root traversal; longer-lived capabilities need a longer-lived owner, and children should receive required collaborators explicitly. Await owner and child lifecycle operations. | | Application root View and Region ownership | Core Application could construct or receive a Region and proxy `showView`, but it read any `currentView` from that Region and did not coordinate Region or root View teardown with Application lifecycle. | The Application's View is its Region's `currentView`, including Views shown directly through the Region. Stop empties the Region's current View. Destroy also destroys a constructed Region, releases a borrowed Region without destroying it, and clears the Region reference. | Changed | Use a Region instance when an external owner controls the host lifetime; use a selector, Region class, or definition object when the Application should own it. Show a new root View from `onStart` after restart. Views shown directly in a borrowed Region are also emptied when the Application stops. | | Custom `destroy` overrides | An override could mutate owned state before calling the v4 base `destroy()` method. Reentrant calls and throwing `before:destroy` handlers did not have one consistent retry boundary. | The synchronous base method for MnObject, View, CollectionView, Behavior, and Region establishes its destruction guard before `before:destroy`. Application owns a separate asynchronous lifecycle and returns its destroy Promise. Cleanup performed before delegating remains outside either guarantee. | Changed | Audit every custom `destroy` override. Synchronous owner overrides must preserve the base reentry boundary. Application overrides must return or await the Promise from the base operation and must not recreate a synchronous teardown path. | | Behavior element retargeting | The undocumented `Behavior#proxyViewProperties()` helper copied the host View's element properties onto the Behavior. | Behaviors share their host's fixed root. `Behavior#setElement()` and `proxyViewProperties()` are removed. | Removed | Choose the host root at construction; do not retarget Behaviors independently. | | Rendering a destroyed View | A destroyed `View#render` could still resolve `getTemplate` before returning, while destroyed `CollectionView#render` behavior was undocumented. | Destroyed View and CollectionView render calls return the same instance without resolving templates, running render lifecycles, changing DOM, or recreating children. No diagnostic is thrown. | Changed | Render only live View and CollectionView instances. | | Adding a child to a CollectionView during or after destruction | Base `CollectionView#addChildView` could inspect or manage a supplied View and restart rendering once destruction began. | The base method returns the supplied View before inspecting the View, index, or options or changing events, ownership, DOM, or lifecycle state. | Changed | Add the child to a live CollectionView instead. Custom overrides own their behavior unless they delegate to the guarded base method. | | Delegating entity events during or after View destruction | Base `View#delegateEntityEvents`, `CollectionView#delegateEntityEvents`, and direct delegation through an attached Behavior could resolve maps and bind new model and collection subscriptions once host destruction began. | The base host methods return the host, and direct `Behavior#delegateEntityEvents` returns the Behavior, without resolving maps or binding handlers once the owning View's destruction starts. Behavior reuse after `Behavior#destroy` while its host remains live is outside this contract. `undelegateEntityEvents` is unchanged. | Changed | No guard is needed for a late base host or attached Behavior delegation call. Use a live View or CollectionView when subscriptions must be established, and undelegate before replacing its model or collection. Custom host and Behavior overrides own their behavior unless they delegate to the guarded base method. | | Binding UI during or after View destruction | Base `View#bindUIElements`, `CollectionView#bindUIElements`, and direct calls through a retained Behavior could query the retained root element and recreate bound UI once host destruction began. | The base host methods return the host, and direct `Behavior#bindUIElements` returns the Behavior, without resolving callable host UI, querying DOM, or binding View or Behavior UI once the owning View's destruction starts. Behavior reuse after `Behavior#destroy` while its host remains live is outside this contract. `unbindUIElements` and the `MN0023` unbound `getUI` diagnostic are unchanged. | Changed | No guard is needed for a late base host or Behavior binding call. Bind only while the owning View or CollectionView is live; continue to unbind explicitly when cleanup is required. Custom host and Behavior overrides own their behavior unless they delegate to the guarded base method. | | Framework errors | Framework invariant failures exposed names and prose messages without stable machine identifiers. | `MarionetteError` is a named export and framework invariant failures expose stable `MNxxxx` codes. | Changed | Catch `MarionetteError` and branch on `error.code`; do not parse message prose or legacy documentation URLs. | | Behavior declarations | Underscore could treat non-array values with numeric `length` as array-like behavior lists. | Arrays are the only list form. Object maps use own enumerable string keys in standard order; inherited, symbol, and non-enumerable keys are excluded, and numeric `length` is an ordinary map entry. | Changed | Use an array for list declarations or an ordinary object for named declarations; do not use generic array-like values. | | UI map ownership | Underscore could treat a UI map with numeric `length` as array-like and skip its other named keys. A literal own `__proto__` key could change the prototype of normalized or bound UI output instead of remaining a UI entry. | UI binding and map-normalization iteration use own enumerable string keys in standard JavaScript own-key order. Numeric `length` is an ordinary key, and literal own `__proto__` remains an own entry without changing output prototypes. Direct `@ui` lookup still accepts any own declared selector key, including a non-enumerable one. Arrays, sparse arrays, and other array-like values are not supported UI maps. | Changed | Supply iterated UI configuration as an ordinary object. Move intended iterated keys onto that object itself; do not use inherited, symbol, or non-enumerable properties or array-shaped maps. | | `@ui` reference validation | Missing `@ui` keys could normalize to an `undefined` selector or fail incidentally later. | Every `@ui.` reference must name an own, declared `ui` key; otherwise Marionette throws `MN0018` during normalization. | Changed | Define the `ui` key or replace the reference with a literal selector. | | `getUI` binding lifecycle | Calling `getUI()` without declared or bound UI elements failed with an incidental `TypeError`. | View, CollectionView, and Behavior throw `MN0023` when `getUI()` is called without a declared `ui` map, before binding, or after unbinding. | Changed | Declare a `ui` map, then render a templated View or call `bindUIElements()` explicitly before `getUI()`; bind again before calling it after unbinding. | | Handler validation | Missing string handlers and invalid non-function values could be silently omitted during delegation or binding. | Every supplied handler must be a function or a string that resolves to a callable method; otherwise Marionette throws `MN0019` before delegation, binding, or selective unbinding. | Changed | Define or remove the named method, supply the handler as a function, or omit the map when unbinding everything. | | Region declaration maps | Underscore could treat a Region map with numeric `length` as array-like and skip its other named keys. | Region declarations and `addRegions` use own enumerable string keys in standard order. Inherited, symbol, and non-enumerable keys are excluded, and numeric `length` is an ordinary Region name. Arrays and other array-like values are not supported as Region declaration maps. | Changed | Supply Region declarations as an ordinary object and move intended definitions onto that object itself. | | Region names | Named Region methods inherited JavaScript property-key coercion, so arrays, objects, and Symbols could become or address Region names incidentally. | View Region names are non-empty strings. The public types require strings. Named registration, lookup, removal, and child operations reject empty names with `MN0032`; unsupported shapes have no guaranteed diagnostic. Explicitly registered string collisions such as `constructor`, `toString`, and `__proto__` remain valid. | Changed | Pass the intended non-empty string name directly; do not rely on property-key coercion. | | Named Region operations | Required View operations could fail with an incidental `TypeError` when the named Region did not exist. | `showChildView`, `detachChildView`, `getChildView`, and `removeRegion` throw `MN0020` for an unknown Region name; `getRegion` and `hasRegion` remain optional lookups. | Changed | Define the Region before using a required operation, or check it with `hasRegion` or `getRegion`. | | Region presence queries | `View#hasRegion` delegated to overridable `getRegion`, so querying an unrendered View rendered it before checking the name. | `hasRegion` checks only the View's own registered Region names without rendering, dispatching through `getRegion`, or changing View state, DOM, UI bindings, or lifecycle events. Missing and inherited-only names return `false`; prototype-collision names such as `constructor` return `true` when explicitly registered as own Regions. Destroyed Views return `false` after their Regions are removed. | Changed | Use `hasRegion` for a side-effect-free stored-ownership check. Use a child operation when rendering, override dispatch, and resolving the Region element are intended. | | Region lookup queries | `View#getRegion` rendered an unrendered View before looking up the Region, so `getRegion(name).show(view)` also rendered the parent implicitly. A non-delegating `getRegion` override could bypass that render. | `getRegion` returns an own registered Region without rendering or changing View state, DOM, UI bindings, or lifecycle events. Child operations now render a live, unrendered View before dispatching through overridable `getRegion`, including non-delegating overrides. Destroyed Views return `undefined` after their Regions are removed. | Changed | Use `getRegion` for a side-effect-free optional lookup. Use `showChildView`, `detachChildView`, or `getChildView` to retain deterministic render-before-lookup behavior; render the parent explicitly before calling a selector Region's `show` directly. | | Region snapshot queries | `View#getRegions` rendered an unrendered View before returning its Region map. | `getRegions` returns a fresh snapshot of own registered Region names without rendering or changing View state, DOM, UI bindings, or lifecycle events. Inherited keys are excluded, own prototype-collision names remain safe own entries, and destroyed Views return an empty snapshot. | Changed | Use `getRegions` for a side-effect-free ownership snapshot. `emptyRegions` remains a mutator: it renders a live, unrendered View before calling overridable `getRegions` and emptying the returned Regions. | | Region owner and name queries | Region ownership was maintained privately as `_parentView` and `_name`; reusing a Region instance or occupied name could leave conflicting private ownership records. | `Region#getOwner()` and `Region#getName()` expose the one current registered relationship without rendering, resolving elements, allocating a second registry, or mutating ownership. Standalone and successfully destroyed Regions return `undefined`. Re-adding the same Region under its current owner and name is a no-op. Registration rejects different-owner, different-name, lifecycle-state, and occupied-name conflicts with `MN0030` before committing them. If a lifecycle hook creates a conflict during ordered `addRegions` processing, earlier entries remain registered while the conflicting and later entries do not. | Added | Use these methods instead of reading private fields. Remove an existing named Region before replacing it, and use a fresh Region instance for another owner. For render-time setup, declare a stable Region in `regions` and only show its child from `onRender`. Keep `currentView` and `hasView()` for the Region's owned child rather than adding a second child lookup API. | | Operating through a destroyed Region | `Region#show` could render and retain a new View after destruction, while `empty`, `reset`, and `detachView` could continue mutating View ownership, DOM, or element caches. | After destruction, `show`, `empty`, and `reset` return the Region without changing it; `detachView` returns `undefined`. `show`, `detachView`, and recursive `destroy` calls are also no-ops while destruction is in progress. `empty` and `reset` remain available during cleanup. | Changed | Use a live Region when the operation must occur. Custom overrides own their behavior unless they delegate to the base method. | | Region destruction timing | `isDestroyed()` became `true` before `reset()` emptied the Region. | `isDestroyed()` becomes `true` after `reset()` completes, before the `destroy` event. It remains `false` in `before:empty` and `empty` handlers invoked during destruction. | Changed | Use the `destroy` event for completed teardown. Keep cleanup overrides synchronous and avoid recursive `empty` or `reset` calls from their own lifecycle handlers. Discard the Region if cleanup throws; later `destroy()` calls do not retry it. | | `onShow` | `Region` invoked `onShow(region, view, options)` for its `show` lifecycle event. | The Region `show` event and `onShow` method convention remain supported. | Preserved | No lifecycle rename is required. | | Native DomApi customization | Applications could replace or partially override Marionette's DomApi globally or per class. | The native DomApi is the default and remains customizable with `setDomApi` or class-level setters. | Documented | Customization applies to `View`, `CollectionView`, and `Region`. | | EventDelegator customization | DOM event delegation was supplied through Backbone view and jQuery behavior. | Native delegation is the default and can be replaced globally with `setEventDelegator` or per class. A complete adapter implements `delegate({ eventName, selector, handler, rootEl })` and returns an idempotent cleanup function for that exact registration; Marionette invokes it at most once. | Changed | Use the [EventDelegator runtime adapter contract](/docs/upgrade-guide.md#eventdelegator-runtime-adapter). Existing registrations retain their original cleanup when configuration changes; the current adapter is selected on the next delegation pass. | | Failed View construction cleanup | If `initialize()` or later constructor setup threw after DOM events, Behaviors, or State were initialized, those owned resources could remain attached to a caller-owned element or instance graph. | Constructor errors propagate without rolling back partially completed initialization. | Preserved | Do not depend on inspecting or retaining a partially constructed instance after an exception. See the [synchronous failure boundary](/docs/lifecycle.md#synchronous-failures). | | Host and Behavior DOM declaration collisions | Marionette flattened every Behavior and host `events` and `triggers` map before asking Backbone to delegate it. Identical event-and-selector keys overwrote earlier declarations according to merge order. | The host and each Behavior own independent delegated listeners. Every matching declaration runs once, without an ordering guarantee among Behavior handlers. | Changed | Remove code that depends on one declaration suppressing another. Give handlers distinct selectors or event types when only one should run, or coordinate the shared action explicitly. | | View DOM event redelegation | `View#delegateEvents(events?)` and `View#undelegateEvents()` refreshed or removed View and Behavior DOM handlers and returned the View. An explicit map replaced the View's configured `events` while retaining triggers and Behavior handlers. `setElement()` dispatched through the public pair. | The public pair remains available on View and CollectionView with the same explicit-map boundary, Behavior and trigger participation, and chainability. Callable maps and current UI selectors are resolved on each delegation pass, existing handlers are removed first, and calls after destruction starts are no-ops. | Preserved | Continue using the pair when declarative DOM configuration changes at runtime. Do not add destroyed-state guards around these calls. A method override owns cleanup or redelegation unless it calls the base method. | | `View#remove` | View inherited Backbone's `remove()` method, which removed its element and stopped listeners without running Marionette's complete destroy lifecycle. | The inherited method is intentionally removed. | Removed | Use `destroy()` for terminal cleanup. Use an owning Region's `detachView()` when the live View must be retained for reuse. | | Imperative `View#delegate` and `View#undelegate` | View inherited Backbone's singular low-level helpers for adding and removing individual delegated handlers. | The inherited helpers are intentionally removed; Marionette owns delegation through declarative maps and the EventDelegator adapter. | Removed | Prefer `events` and `triggers`, then call `delegateEvents()` to refresh them. Use native listeners or a custom EventDelegator only for interactions that cannot be expressed declaratively. | | Delegated DOM event semantics | Backbone delegated View events through jQuery, including jQuery special-event handling, namespaces, `return false` shorthand, and extra arguments supplied through jQuery triggering. | Delegated handlers receive a native event: `currentTarget` remains the View root and Marionette sets `delegateTarget` to the closest matching descendant, invoking once even when multiple ancestors match. Non-bubbling `mouseenter` is not emulated. Namespaces, `return false`, and extra trigger arguments are not native contracts. | Changed | Use bubbling native events or direct listeners, explicit event methods, and `CustomEvent.detail` as appropriate. See [Native delegation versus jQuery events](/docs/upgrade-guide.md#native-delegation-versus-jquery-events). The optional jQuery DomApi does not change event delegation. | | Adapter overlay input inheritance | DomApi and EventDelegator overlays could contribute inherited enumerable properties. | DomApi overlays copy own enumerable string and symbol properties and preserve a literal own `__proto__` property without changing the adapter prototype. EventDelegator configuration replaces the complete adapter object instead of overlaying it. | Changed | Move intended DomApi overrides onto the supplied object itself. Provide a complete EventDelegator with a callable `delegate` method. | ## Reading changed and removed rows The highest-impact migration boundaries are: - update the package name and imports before addressing runtime behavior; - keep default-namespace and `Mn.Object` compatibility out of new v5 code; - explicitly opt into Backbone or jQuery compatibility only where an application still needs it; - resolve `View` and `CollectionView` selector strings before construction, while leaving Region selector strings unchanged; and - audit code that depends on `$el`, jQuery-shaped `view.$()` results, or the selected adapter's content replacement and cleanup semantics. The full ordered migration procedure and remaining before-and-after examples are tracked in issue #147. ### Await Application readiness V4 startup completed synchronously, so code commonly dispatched work on the next line: ```javascript app.start(); dispatchInitialRoute(); ``` V5 awaits a Promise returned by `onBeforeStart`. Await `start()` and dispatch only when that exact startup reaches running state: ```javascript const App = Application.extend({ onBeforeStart(app, options, { signal }) { return loadInitialData({ signal }); } }); const app = new App(); if (await app.start()) { dispatchInitialRoute(); } ``` A `false` result means a later stop, restart, or destroy superseded this startup. It is not a failure and does not need a `catch`. A current readiness failure rejects and should use the application's ordinary error path. Marionette aborts the readiness signal before replacement readiness starts, so pass it to cancellable work rather than inventing a parallel cancellation hook. [Canonical source](/docs/markdown/docs/migration-from-v4.md) · [Source identity](/docs/manifest.json) --- Document: upgradeGuide.md Canonical URL: https://marionettejs.com/docs/upgrade-guide/ Markdown URL: https://marionettejs.com/docs/upgrade-guide.md Reading SHA-256: 00cbeb1cfe92c5af4442ca7b2d45a9747175c760a9f68b64569d987a200141de # Upgrade guide ## From backbone.marionette.js See the [v4-to-v5 compatibility ledger](/docs/migration-from-v4.md) for the current public behavior boundary. Final migration documentation is tracked in [issue #147](https://github.com/marionettejs/marionette/issues/147). ## Use the included TypeScript declarations The `marionette` package includes declarations for its public exports in ESM and CommonJS. Core declarations support TypeScript 6 and 7 with NodeNext or bundler resolution. Import instance and configuration types from `marionette`; a separate core type package is not needed. Optional packages keep their own declarations and compiler support. Both `.extend()` and direct native subclasses remain available. A native class's inherited `.extend()` needs an explicit constructor: default forwarding uses `parent.apply`, which cannot call a native class. Some native overrides after `.extend()` configuration, especially prototype `options` factories, encounter TypeScript's distinction between methods and properties. Define those overrides with `.extend()`, or start the native subclass from the public base. Custom constructors can replace the instance. Their declared object return is the constructed type; an unknown return stays unknown. See the [constructor typing guidance](https://github.com/marionettejs/marionette/blob/b06750c507494441f0b2298766b70087e45346a2/docs/maintainers/types.md) for preserving the receiver through further extensions and the limits of return annotations. ## Managed children use Marionette's lifecycle Regions, CollectionView children, and empty Views use Marionette View or CollectionView instances. Automatic Backbone View lifecycle adaptation is removed, including `supportsRenderLifecycle`, `supportsDestroyLifecycle`, and the fallback from `destroy()` to `remove()`. Wrap an existing non-Marionette view in a Marionette View and own its rendering and cleanup explicitly. See the [wrapper example](/docs/region.md#wrapping-a-non-marionette-view). Behaviors also keep their initial host element; their internal `_syncElement()` retargeting method is removed. Event redelegation still refreshes their handlers. ## Construct Views before showing them `Region#show` and `View#showChildView` require a Marionette View instance in v5. They no longer construct a hidden base View from a template function, string, or View-options object. Make the allocation and ownership explicit: ```js import { View } from 'marionette'; // v4 parent.showChildView('heading', 'Edit program'); parent.showChildView('content', { template, templateContext: { section: 'main' } }); // v5 parent.showChildView('heading', new View({ template: () => 'Edit program' })); parent.showChildView('content', new View({ template, templateContext: { section: 'main' } })); ``` ## Configure model and collection data - Marionette core no longer reads Backbone-specific `cid`, `attributes`, `get`, `models`, `indexOf`, or structural event payloads. - Plain object models and array collections work through the default DataApi. - `DataApi.models(collection)` replaces the pre-stable `DataApi.items(collection)` name without a compatibility alias. ```js // before const models = DataApi.items(collection); // v5 const models = DataApi.models(collection); ``` - View templates with a collection and no model now receive the result of `serializeCollection()` on the `models` property. By default, that result is an array of serialized values. Replace the pre-stable `items` property without retaining both names. ```js // before template: ({ items }) => items.map(renderModel) // v5 template: ({ models }) => models.map(renderModel) ``` - Applications whose Views use Backbone models or collections must select its DataApi before constructing those Views: ```sh npm install @mnjs/adapters backbone ``` ```js import BackboneApi from '@mnjs/adapters/backbone'; import { setDataApi } from 'marionette'; setDataApi(BackboneApi); ``` Configure `setStateApi(BackboneApi)` separately only when declarative `stateEvents` observe a Backbone state source. Using Backbone.Router alone requires neither adapter. See [Choosing integrations](/docs/choosing-integrations.md). - Other data sources can configure `setDataApi` with methods for identity, reads, serialization, ordered model snapshots, subscriptions, and collection observation. XState actors can use `@mnjs/adapters/xstate`. See [Data API](/docs/data-api.md). - State owners return the exact supplied source from `getState()`. Use `createState(options)` for an owned source, and configure `setStateApi` when declarative `stateEvents` need observation. The v5 alpha concrete `State` export is removed. See [State sources and StateApi](/docs/state.md). - `Application#getParentApp()` and `Application#getRootApp()` are removed. Pass required collaborators to child Applications explicitly when constructing them instead of traversing upward. - Replace `children.findByModelCid(cid)` with `children.findByModel(model)`. ## Native data package - Use `Model.toObject()` and `Collection.toArray()` for plain attribute data. `toJSON()` is removed from the native package; serialize those plain values explicitly with `JSON.stringify`. Template data comes from attributes and is independent of conversion overrides. - `Collection.touch()`, `swap()`, and `replace()` are removed. Update an existing model with `model.set()` and bind child rendering with `modelEvents`. Use `remove`/`add` or `reset` when replacing membership intentionally. - `Collection.move(modelOrId, index)` retains existing models and child Views for explicit list ordering. Listen to `sort`, which both `move` and `sort` emit; the native `reorder` event is removed. - Native DataApi keys are model `cid` values, so application ids can change without changing child identity. Keep application ids unique for unambiguous collection lookup. - Collection notifications now follow ordinary synchronous events. They do not combine nested mutations or recover missed notifications after a listener throws. Schedule structural mutations requested by collection or child lifecycle listeners after the current notification has returned. ## CollectionView child rendering Collection changes, `sort()`, and `filter()` share the child-rendering path. Existing visible children stay mounted, including with a custom comparator or filter. `attachHtml` receives only elements that need attaching; it is no longer called just to reorder mounted children. Reordering uses `Dom.moveEl`. `Dom.swapEl` is removed; `swapChildViews()` exchanges the children using at most two `Dom.moveEl` calls. Custom DomApi implementations only need `moveEl` for these placement operations. The child-render pass restores focus and text selection if a DOM move loses them; a direct swap only preserves them when the browser supports state-preserving moves. Only a numeric `addChildView` index bypasses sorting and filtering. Passing `null` or options without an index now follows the same comparator/filter path as omitting the index. `before:render:children` and `render:children` receive all visible children, regardless of which templates needed rendering. Do not treat that argument as an added-children or updated-children list. Overrides of `sort()` and `filter()` own their behavior. Call the parent method when you want its sorting, filtering, and rendering steps. The early v5 fallback that forced a render after an override has been removed. ## CollectionView source order and presentation sorting - A normalized DataApi `reorder` or `update` keeps keyed children aligned with the collection source order while `sortWithCollection` is enabled. - `viewComparator: false` disables the separate presentation comparator; it no longer freezes the current child order against structural source changes. - Set `sortWithCollection: false` when a CollectionView must preserve manually managed child order instead of following the source. - An immutable update that replaces a model with a different object at the same stable key recreates that child View. Do not retain references to the old child across such an update. ## Underscore is no longer a peer dependency - Marionette v5 core does not import or declare Underscore as a peer dependency. - Remove an explicit Underscore installation if it existed only for Marionette. Keep it as an application dependency when your own code uses it, such as an `_.template` supplied to a View. - Applications using Backbone still receive Underscore through Backbone's own declared dependency; the Marionette integration does not import it. ## View roots are fixed at construction `View#setElement()` and `CollectionView#setElement()` are removed. Choose the root through `new View({ el })` or `new CollectionView({ el })`; both also accept an `el` factory. Without an `el`, Marionette creates one from `tagName`. The public instance `el` is readonly. Direct reassignment is unsupported. Render into the existing root and use Regions to move or detach the View. When another system replaces the root, destroy the old View and create a new owner for the replacement element. Keep persistent state in the model or an externally owned state source. Custom `setElement()` overrides are no longer called during construction; move initialization to `initialize()` or an `el` factory, as appropriate. ## View `el` is element-only - `View` (and `CollectionView`) accept a DOM element for `el` in v5. Selector strings are no longer resolved, and jQuery collections must be unwrapped. - v4 inherited string-`el` resolution from `Backbone.View._ensureElement`, which used jQuery to look up the selector. v5 drops `Backbone.View` inheritance and the default jQuery dependency, so the string-resolution path goes with them. - v5 now throws a `ViewError` with a migration hint on construction when a string is passed, instead of silently storing the raw string as `view.el` and failing later in DOM code. - Migration: resolve at the call site. ```js // v4 new View({ el: '#root' }); // v5 new View({ el: document.querySelector('#root') }); ``` - `Region` continues to accept selector strings. That API is Marionette-native (the Region abstraction has always been "where to mount"), not inherited from Backbone, so it is preserved. When the mount point is already resolved, pass its native element rather than a jQuery collection. ## Refresh View root attributes explicitly Use `renderAttributes()` when `attributes`, `id`, or `className` changed but the View's template content and owned children should remain in place: ```js const RowView = View.extend({ attributes() { return { 'aria-selected': this.selected ? 'true' : 'false' }; }, className() { return this.selected ? 'selected' : null; } }); row.selected = true; row.renderAttributes(); ``` This explicit refresh is separate from `render()` and emits no render lifecycle events. With the default DomApi, only explicit `null` removes a named attribute; `undefined` and omitted keys leave existing attributes untouched. Custom DomApi adapters must implement the same `setAttributes` behavior. Attribute maps use DOM attribute names (`class`, `for`), not property names (`className`, `htmlFor`). The View-level `className` option still works. Earlier v5 alphas also assigned matching element properties; v5 now applies attributes only. Update live form values and custom element properties explicitly on `el`. For boolean HTML attributes, use `disabled: isDisabled ? '' : null` instead of `disabled: isDisabled`. Other values, including `false`, are converted to strings; ARIA attributes such as `aria-selected: false` therefore retain `"false"`. ## jQuery DOM compatibility v5 core does not depend on jQuery and does not create `$el`. Configure the optional DOM adapter when the application needs jQuery queries and content operations: ```js import $ from 'jquery'; import { View } from 'marionette'; import JQueryDomApi from '@mnjs/adapters/dom/jquery'; const JQueryView = View.extend({ initialize() { this.$el = $(this.el); } }); JQueryView.setDomApi(JQueryDomApi); ``` Install `@mnjs/adapters` and `jquery` for this integration. The fixed root makes the application-owned wrapper valid for the View's lifetime. CollectionViews and Behaviors can initialize `$el` in the same way. A subclass overriding `initialize()` must also perform any setup it needs from its application base. Core View, CollectionView, and Behavior types no longer take a `Wrapped` generic. `ViewInstance` becomes `ViewInstance`, and `DomApi` becomes `DomApi`. Declare `$el: JQuery` on application subclasses that provide it. Use a TypeScript `declare` field so it does not overwrite the wrapper initialized by the base constructor. This integration does not restore Backbone.View inheritance. Resolve selector strings or unwrap jQuery collections before supplying a View `el`. ## Native delegation versus jQuery events The default EventDelegator uses `addEventListener` on the View's root element. During a delegated handler, the native `event.currentTarget` is therefore the View's root `el`. Marionette sets `event.delegateTarget` to the closest matching descendant between the original target and that root. If nested ancestors match the same selector, only that closest match invokes the handler; Marionette does not invoke it again for every matching ancestor. This is a native DOM contract, not an emulation of jQuery's event system: - `mouseenter` does not bubble, and Marionette does not provide jQuery's special delegated `mouseenter` handling. Use a bubbling event such as `mouseover` with an appropriate `relatedTarget` check, or bind `mouseenter` directly to the intended element. - A name such as `click.menu` is a literal native event type, not a `click` event in a jQuery namespace. Marionette already tracks and removes a View's delegated listeners; application-owned native listeners should retain their own callbacks or abort signals for cleanup. - Returning `false` from a handler does not prevent the default action or stop propagation. Call `event.preventDefault()` and/or `event.stopPropagation()` explicitly. - Browser `dispatchEvent()` supplies only the event object to a handler; jQuery trigger arguments are not forwarded. Put application data in a `CustomEvent`'s `detail`, or use Marionette events when positional arguments are part of the application contract. - Delegated `focus` and `blur` handlers run during capture, before listeners on the target element. A Marionette trigger stops propagation by default, so set `stopPropagation: false` on a focus or blur trigger when the target must also receive the event. Marionette does not translate these names to `focusin` or `focusout`. The optional jQuery DomApi changes query and DOM-manipulation operations only; it does not replace the native EventDelegator. Applications with a verified need for different delegation semantics can provide an explicit adapter through `setEventDelegator`. ### EventDelegator runtime adapter An EventDelegator is a complete adapter with one method: `delegate({ eventName, selector, handler, rootEl })`. It registers that handler and returns an idempotent cleanup function for the exact registration, including its original root and listener options. Marionette stores the cleanup and calls it during redelegation or destruction. Registration and cleanup errors stop the operation; failed construction is not rolled back. The adapter must not mutate View internals. See the EventDelegator Adapter section of the DOM interactions API documentation for the complete timing, error, and cleanup contract. ## Atomic Radio migration Marionette v5 owns the `Radio` singleton used by `channelName`, `radioEvents`, and `radioRequests`. It is not the singleton exported by `backbone.radio`. Replace every application import in one migration: ```js // v4 import Radio from 'backbone.radio'; // v5 import { Radio } from 'marionette'; ``` This includes publishers and requesters that do not instantiate a Marionette class. Leaving either import in the application creates two channels with the same name on disconnected buses, so messages and requests can disappear without an exception. Do not bridge, mirror, or run both singletons as a compatibility strategy. Replace `Radio.DEBUG = true` with `Radio.setDebug()` and disable it with `Radio.setDebug(false)`. Import the Requests mixin with `import { Requests } from '@mnjs/radio'` and compose it into an object with `Object.assign`. Import `Channel` from the same package for standalone channels, or use `new runtime.Radio.Channel(name)` for runtime-specific logging. Standalone channels are not registered; their owner calls `reset()` when finished. `Radio.log` and `Radio.debugLog` remain replaceable hooks, scoped to each Radio instance. `setDebug(false)` also suppresses custom warning hooks. Existing channels use replacement hooks immediately, and hooks receive their Radio as `this`. Request/reply methods are not mixed into `Application`, `Behavior`, `CollectionView`, `MnObject`, `Region`, or `View` instances. Replace an alpha-only instance call with an explicit channel: ```js // before view.reply('status:current', getStatus); // v5 Radio.channel('status').reply('status:current', getStatus); ``` Use `radioRequests` on `Application` or `MnObject` for declarative replies on their configured channel. Any owner can use `bindRequests(channel, bindings)` when it receives the channel explicitly. Pair that registration with `unbindRequests(channel)` in the owner's cleanup hook; imperative bindings to an arbitrary channel are not automatically tracked for destruction. Unbinding this way removes only that owner's replies. ## `detachContents` policy - The default native DomApi `detachContents(el)` clears the element via `el.textContent = ''`. Children are removed from `el`; callers retaining a child reference still retain its listeners and data. - v4 used jQuery's `$(el).contents().detach()`, which is jQuery's documented detach-for-reinsertion path. It removes children from `el` while preserving jQuery's internal handler/data bookkeeping on those elements. - Native node removal does not call jQuery's cleanup machinery either. Referenced detached nodes retain native listeners, jQuery `.on()` handlers, and `.data()` values with both implementations. Detachment alone is not a reason to add jQuery. This differs from content replacement with jQuery's `.html()`, which cleans jQuery handlers and data from removed descendants. - Applications needing jQuery query and content-operation semantics can select the optional jQuery DomApi adapter at app boot: ```js import { setDomApi } from 'marionette'; import JQueryDomApi from '@mnjs/adapters/dom/jquery'; setDomApi(JQueryDomApi); ``` The adapter's `detachContents(el)` calls `$(el).contents().detach()`, matching the v4 behavior. - The optional jQuery adapter is described in the [installation guide](/docs/installation.md#jquery-dom-adapter-is-optional). ### DOM adapter setup Morphdom and Lit now live under `@mnjs/adapters/dom/` and export DOM operation objects rather than class installers. Update imports from the former `render` directory; those package subpaths are removed. ```js import MorphdomDomApi from '@mnjs/adapters/dom/morphdom'; import LitDomApi from '@mnjs/adapters/dom/lit-html'; MorphView.setDomApi(MorphdomDomApi); LitView.setDomApi(LitDomApi); ``` Custom renderers must return their template result. `undefined` is passed to `Dom.setContents` and clears contents with the supplied native, jQuery, Morphdom, and Lit adapters; it no longer signals a renderer that performed its own DOM update. Put direct DOM updates in `setContents` instead. Lit uses element-only `notifyAttach` and `notifyDetach` hooks and no longer patches View lifecycle methods. Detachment and destruction disconnect directives without emptying their DOM. With attachment monitoring disabled, deliver these notifications from application code. Lit event handlers use the element as their receiver rather than the View; use a closure for View access. ## Shared utilities Reusable helpers live in `@mnjs/utils`. Core and native data use the same implementations; install the matching version directly when importing helpers into your own components. Existing public Marionette helper exports still refer to those functions. Source-file imports are not package entry points. Core ESM and CommonJS builds import `@mnjs/utils` and `@mnjs/radio`. Browser projects loading raw ES modules must map both packages in their import map, or use a bundler. Standalone UMD builds remain self-contained. ### Native object copying Use object spread or `Object.assign` instead of the removed `@mnjs/utils` `assignOwn` and `assignIn` helpers. Configuration copies follow native own-property semantics, including enumerable symbol keys; string sources expose character keys instead of being silently ignored. There is no getter-ordering contract beyond the chosen native operation. `extend` retains inherited enumerable parent statics and defines subclass properties so they can shadow inherited getters. Dynamic model and event keys such as `__proto__` remain ordinary data properties. ### Standalone Events, Radio, and data `@mnjs/utils` owns the shared `Events` implementation. `@mnjs/radio` exports the default `Radio` and the `createRadio()` factory. Core continues to export the same Events, Error, and default Radio within each module format. `createMarionette()` continues to create an isolated Radio for each runtime. `@mnjs/data` now depends only on utils; core is no longer a peer dependency. Standalone data and messaging consumers do not need to install Marionette core. These packages keep the same version and release together with core and adapters. [Canonical source](/docs/markdown/upgradeGuide.md) · [Source identity](/docs/manifest.json) --- Document: errors/MN0001 Canonical URL: https://marionettejs.com/errors/MN0001/ Markdown URL: https://marionettejs.com/errors/MN0001.md Reading SHA-256: 8b884a332790d23a2ca9947db27e4e4ca800690db2d589a44ca31438605d7848 # MN0001: view el must be dom element Status: retired Objects: CollectionView, View Category: dom Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0002 Canonical URL: https://marionettejs.com/errors/MN0002/ Markdown URL: https://marionettejs.com/errors/MN0002.md Reading SHA-256: 7414f35dfbf770a2809704c5d788ea9c27f72a35f90b290844b94c5e4214a0e7 # MN0002: region el type invalid Status: retired Objects: Region Category: dom Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0003 Canonical URL: https://marionettejs.com/errors/MN0003/ Markdown URL: https://marionettejs.com/errors/MN0003.md Reading SHA-256: cff081eb2f064d8890ba1dbf2add28adfbde27ad6cbd8e2b07f547bc40efcf13 # MN0003: view already owned Status: active Objects: CollectionView, Region, View Category: ownership Severity: error ## Remediation Detach or remove the view from its current Region or CollectionView before showing it elsewhere, or create a new view instance. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0004 Canonical URL: https://marionettejs.com/errors/MN0004/ Markdown URL: https://marionettejs.com/errors/MN0004.md Reading SHA-256: 7a5f0a0389cbad2c7cea1572dd06149a84f58fdb415712f24b00adea1e84df1a # MN0004: region el required Status: active Objects: Region Category: dom Severity: error ## Remediation Configure the Region with an el selector or DOM element before using it. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0005 Canonical URL: https://marionettejs.com/errors/MN0005/ Markdown URL: https://marionettejs.com/errors/MN0005.md Reading SHA-256: 3808131e41585745d9aa9b22376f30c02b6d10cb4e01106becbd6f64a1a58584 # MN0005: region el not found Status: active Objects: Region Category: dom Severity: error ## Remediation Render the parent View before direct selector-backed Region operations, ensure the selector resolves within its parent element, or explicitly allow a missing element where supported. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0006 Canonical URL: https://marionettejs.com/errors/MN0006/ Markdown URL: https://marionettejs.com/errors/MN0006.md Reading SHA-256: b18d4b965ed0f2d17ed604f3c0bf6b43125691c1a314c618de0b66b417e21d2f # MN0006: region view required Status: retired Objects: Region Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0007 Canonical URL: https://marionettejs.com/errors/MN0007/ Markdown URL: https://marionettejs.com/errors/MN0007.md Reading SHA-256: 04972e5527754b44a3aa71001a6ee8d7188eca5635e17ba747571004588fdbcd # MN0007: region view destroyed Status: active Objects: Region, View Category: lifecycle Severity: error ## Remediation Create a new View instance instead of attempting to show a destroyed view. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0008 Canonical URL: https://marionettejs.com/errors/MN0008/ Markdown URL: https://marionettejs.com/errors/MN0008.md Reading SHA-256: 8fbfb8f6471f15a5da7f16c055656b784ef440e994483b86aad9a27ec42f3a60 # MN0008: region definition invalid Status: retired Objects: Application, Region, View Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0009 Canonical URL: https://marionettejs.com/errors/MN0009/ Markdown URL: https://marionettejs.com/errors/MN0009.md Reading SHA-256: d584d785cd1beef5b2c4697906506ab0000f1a8c40a67d61dacdff59b086d1c1 # MN0009: event bindings invalid Status: retired Objects: Application, Behavior, CollectionView, MnObject, Region, View Category: communication Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0010 Canonical URL: https://marionettejs.com/errors/MN0010/ Markdown URL: https://marionettejs.com/errors/MN0010.md Reading SHA-256: 30136b709d90ea4a6e762f9090469017b8bcd6799062312bc271bb713dddb107 # MN0010: request bindings invalid Status: retired Objects: Application, Behavior, CollectionView, MnObject, Region, View Category: communication Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0011 Canonical URL: https://marionettejs.com/errors/MN0011/ Markdown URL: https://marionettejs.com/errors/MN0011.md Reading SHA-256: 777ded415378998f276f7a7eac30fb679907188e08f57a1ba7a83600133c6126 # MN0011: collection view child view required Status: active Objects: CollectionView Category: configuration Severity: error ## Remediation Configure childView with a View class or a function that returns a View class. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0012 Canonical URL: https://marionettejs.com/errors/MN0012/ Markdown URL: https://marionettejs.com/errors/MN0012.md Reading SHA-256: f9997c022e1d503a9df5debd955becbc82876f68a0ae9fda4d6bb188ca6e4811 # MN0012: collection view child view invalid Status: retired Objects: CollectionView Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0013 Canonical URL: https://marionettejs.com/errors/MN0013/ Markdown URL: https://marionettejs.com/errors/MN0013.md Reading SHA-256: 3c32e8ea72b25150390f9ec20be0052b0b94cf4c7df1efbfbd98968bd5f2d125 # MN0013: collection view container not found Status: active Objects: CollectionView Category: dom Severity: error ## Remediation Ensure childViewContainer resolves to an element within the rendered CollectionView. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0014 Canonical URL: https://marionettejs.com/errors/MN0014/ Markdown URL: https://marionettejs.com/errors/MN0014.md Reading SHA-256: f3ef961d575cb45e25888b11b456cf9aa1a3776a8e49cb899e73b0d28b92a2c1 # MN0014: collection view filter invalid Status: retired Objects: CollectionView Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0015 Canonical URL: https://marionettejs.com/errors/MN0015/ Markdown URL: https://marionettejs.com/errors/MN0015.md Reading SHA-256: 972be450f3de0a0a30aec3e33cdd914c47b9d0d9777948706a2453ca05920820 # MN0015: collection view swap non children Status: active Objects: CollectionView Category: ownership Severity: error ## Remediation Pass two views currently owned by the CollectionView to swapChildViews. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0016 Canonical URL: https://marionettejs.com/errors/MN0016/ Markdown URL: https://marionettejs.com/errors/MN0016.md Reading SHA-256: e2a5811f4e6c418cb4874a6e576d040d7e4b5aa167ba997c5dcc6c23f8343f21 # MN0016: behavior definition invalid Status: retired Objects: Behavior, CollectionView, View Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0017 Canonical URL: https://marionettejs.com/errors/MN0017/ Markdown URL: https://marionettejs.com/errors/MN0017.md Reading SHA-256: 9a6d76979e2852833daee4dee719ee3f8c180dbe83495c805f7aa891d1a77d17 # MN0017: radio channel name required Status: active Objects: Radio Category: communication Severity: error ## Remediation Pass a non-empty channel name when creating or accessing a Radio channel. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0018 Canonical URL: https://marionettejs.com/errors/MN0018/ Markdown URL: https://marionettejs.com/errors/MN0018.md Reading SHA-256: a2a752ad787afc3b9cac901a9348097634c0a18882b6cb7f1968a055ec75e946 # MN0018: ui reference invalid Status: active Objects: Behavior, CollectionView, View Category: configuration Severity: error ## Remediation Use @ui. with a non-empty own key whose value is a string selector, or replace the reference with a literal selector. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0019 Canonical URL: https://marionettejs.com/errors/MN0019/ Markdown URL: https://marionettejs.com/errors/MN0019.md Reading SHA-256: d5142f998935339dfd8f09f5115ad43e10d6adbf0dafa44742f534d04dc740a8 # MN0019: handler not callable Status: active Objects: Application, Behavior, CollectionView, MnObject, Region, View Category: communication Severity: error ## Remediation Provide a function or the string name of a callable method on the binding context. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0020 Canonical URL: https://marionettejs.com/errors/MN0020/ Markdown URL: https://marionettejs.com/errors/MN0020.md Reading SHA-256: 57a621e9c15427179f461a5e0b7c168355e5944cbe2f23e633a30dfc21f8cfaf # MN0020: named region not found Status: active Objects: View Category: configuration Severity: error ## Remediation Define the named Region before using child-View or Region-removal operations, or use getRegion or hasRegion for optional lookup. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0021 Canonical URL: https://marionettejs.com/errors/MN0021/ Markdown URL: https://marionettejs.com/errors/MN0021.md Reading SHA-256: bd7727d567d1f0af9efc179582c73765fdc0d5d16f4a1e5ed1aa00a973c0cd0d # MN0021: radio channel not found Status: active Objects: Radio Category: communication Severity: error ## Remediation Create the named channel with Radio.channel(name) before resetting it, or call Radio.reset() with no arguments to reset all existing channels. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0022 Canonical URL: https://marionettejs.com/errors/MN0022/ Markdown URL: https://marionettejs.com/errors/MN0022.md Reading SHA-256: e3d7711cb115fbe3de335e0c81f8e71d59e1e261ecdc5f1bd6e80de9e80159b5 # MN0022: collection view empty view invalid Status: retired Objects: CollectionView Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0023 Canonical URL: https://marionettejs.com/errors/MN0023/ Markdown URL: https://marionettejs.com/errors/MN0023.md Reading SHA-256: f2abdd262d39f2c538bd0f80e1b713057221eeeb5a5e47ccb56aa1a002baec04 # MN0023: ui elements unavailable Status: active Objects: Behavior, CollectionView, View Category: lifecycle Severity: error ## Remediation Declare a ui map, then render the View or explicitly bind its UI elements before calling getUI; bind them again before calling getUI after unbinding. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0024 Canonical URL: https://marionettejs.com/errors/MN0024/ Markdown URL: https://marionettejs.com/errors/MN0024.md Reading SHA-256: cd1a41e24402d7f82eab71ccb297220a296f562afa48db3eb7e0873dca65050a # MN0024: child container argument invalid Status: active Objects: CollectionView Category: configuration Severity: error ## Remediation Pass nonnegative integer counts. Reducing an empty child container requires an initial value. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0025 Canonical URL: https://marionettejs.com/errors/MN0025/ Markdown URL: https://marionettejs.com/errors/MN0025.md Reading SHA-256: d3d10535d2134bee64f3ef1d11a78ccb9752d622edc08ff67eacaacb1fb67f37 # MN0025: child container method not callable Status: retired Objects: CollectionView Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0026 Canonical URL: https://marionettejs.com/errors/MN0026/ Markdown URL: https://marionettejs.com/errors/MN0026.md Reading SHA-256: efd8ec7e7f97ef0e88be75ef41d5f07e965b7c5d2002e9573b598d57777e696b # MN0026: entity event name unsafe Status: active Objects: Application, Behavior, CollectionView, MnObject, Region, View Category: communication Severity: error ## Remediation Rename an own __proto__ entry in an entity-event map before binding or selectively unbinding it. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0027 Canonical URL: https://marionettejs.com/errors/MN0027/ Markdown URL: https://marionettejs.com/errors/MN0027.md Reading SHA-256: 7ee72950da25fc65cb3fc2f2e14571c2efc485461e77e2ee6104ea224c2ea5e1 # MN0027: feature name invalid Status: retired Objects: Behavior, CollectionView, View Category: configuration Severity: error ## Remediation The v5 feature registry is removed. Configure child event prefixes per View, trigger behavior per trigger, and application values through State or explicit configuration. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0028 Canonical URL: https://marionettejs.com/errors/MN0028/ Markdown URL: https://marionettejs.com/errors/MN0028.md Reading SHA-256: d1f1c5354fe123e9f31c0cd086c60a3364d80ec7385b916a09b8b4068a8ad760 # MN0028: region destroyed operation Status: retired Objects: Region Category: lifecycle Severity: error ## Remediation Calls to show, empty, or reset after Region destruction are lifecycle-safe no-ops. Use a live Region when the operation must take effect. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0029 Canonical URL: https://marionettejs.com/errors/MN0029/ Markdown URL: https://marionettejs.com/errors/MN0029.md Reading SHA-256: 619151985ce25aee4a135a8b7fcc50c8558de8dd928c8644f6e55d6aa2efe99b # MN0029: view destroyed set element Status: retired Objects: CollectionView, View Category: lifecycle Severity: error ## Remediation Calls to setElement after View or CollectionView destruction begins are lifecycle-safe no-ops. Use a live instance when element replacement must take effect. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0030 Canonical URL: https://marionettejs.com/errors/MN0030/ Markdown URL: https://marionettejs.com/errors/MN0030.md Reading SHA-256: dd3339073a8895dfcfc482366670d27d3f0b4d6785c58c0714b82ea45a3c7bcd # MN0030: region registration conflict Status: active Objects: Region, View Category: ownership Severity: error ## Remediation Register a live, unowned Region under an unused name; remove an existing named Region before replacing it and use a fresh Region instance for a different owner. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0031 Canonical URL: https://marionettejs.com/errors/MN0031/ Markdown URL: https://marionettejs.com/errors/MN0031.md Reading SHA-256: dcbfdc1c34fbdb9594182c85bf8b80d890da863158406bb559f7a9b89fbec8bf # MN0031: application registration conflict Status: active Objects: Application Category: ownership Severity: error ## Remediation Register a live, unowned Application instance under an unused non-empty string name; use hasChildApp before constructing a dynamic child when allocation must be avoided. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0032 Canonical URL: https://marionettejs.com/errors/MN0032/ Markdown URL: https://marionettejs.com/errors/MN0032.md Reading SHA-256: 677781cf631fd60c192965e10a41f08e419ca6df1e5f82730c080fb39b271931 # MN0032: region name invalid Status: active Objects: View Category: ownership Severity: error ## Remediation Pass a non-empty string name to a named Region operation. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0033 Canonical URL: https://marionettejs.com/errors/MN0033/ Markdown URL: https://marionettejs.com/errors/MN0033.md Reading SHA-256: dd23595f7ace41f75ed90f02312f29a8fcb1fc942e77672c5ee6f20c5155f94c # MN0033: merge options keys invalid Status: retired Objects: Application, Behavior, CollectionView, MnObject, Region, View Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0034 Canonical URL: https://marionettejs.com/errors/MN0034/ Markdown URL: https://marionettejs.com/errors/MN0034.md Reading SHA-256: a7cad34a588c69fd2e1e082310a7b8571891b31abec06009e034f2fa9de90f40 # MN0034: state key invalid Status: retired Objects: StateApi Category: configuration Severity: error ## Remediation The concrete v5 alpha State key validation is removed. Use the selected source's native key contract. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0035 Canonical URL: https://marionettejs.com/errors/MN0035/ Markdown URL: https://marionettejs.com/errors/MN0035.md Reading SHA-256: 97f7c4a427ef5572b99cc65ed904e7a39261389dbf2bb503361ff1648388d63c # MN0035: state ownership conflict Status: retired Objects: Behavior, CollectionView, MnObject, View Category: ownership Severity: error ## Remediation The concrete v5 alpha State ownership rule is removed. Supplied sources are borrowed and may be shared by multiple owners; createState results are owned and disposed by their owner. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0036 Canonical URL: https://marionettejs.com/errors/MN0036/ Markdown URL: https://marionettejs.com/errors/MN0036.md Reading SHA-256: 53b7deb4f31876430d9c8ff04fcc744d1496897ce0be96e8d00cbe0588955e3e # MN0036: event delegator contract invalid Status: retired Objects: Behavior, CollectionView, View Category: configuration Severity: error ## Remediation Use the documented argument types. Marionette no longer emits a dedicated runtime diagnostic for this unsupported input shape. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0037 Canonical URL: https://marionettejs.com/errors/MN0037/ Markdown URL: https://marionettejs.com/errors/MN0037.md Reading SHA-256: 10c30f6d32962e0606cbc62331c7f70c346e44bd1177c1517c5603eddb744752 # MN0037: adapter observation unsupported Status: active Objects: Application, Behavior, CollectionView, MnObject, View Category: configuration Severity: error ## Remediation Configure a StateApi or DataApi that can observe the selected source, or remove the declarative event map. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0038 Canonical URL: https://marionettejs.com/errors/MN0038/ Markdown URL: https://marionettejs.com/errors/MN0038.md Reading SHA-256: 3042b84a37efe4dba22f70d2831b7b3e630c4aceb16a48a147741bdc6be83786 # MN0038: adapter cleanup invalid Status: retired Objects: Application, Behavior, CollectionView, MnObject, View Category: configuration Severity: error ## Remediation DataApi and StateApi adapters must return cleanup functions. Core no longer wraps or validates cleanup on each registration. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/MN0039 Canonical URL: https://marionettejs.com/errors/MN0039/ Markdown URL: https://marionettejs.com/errors/MN0039.md Reading SHA-256: 9d5d87c884052f20a0213ea7b27d3a3f2c891826337f82ab4941ae4e1bbc45d6 # MN0039: collection data contract invalid Status: active Objects: CollectionView Category: configuration Severity: error ## Remediation Return an ordered array with unique stable keys and emit a valid reorder, reset, or update structural record. [Diagnostic catalog](/errors/index.md) · [Source identity](/docs/manifest.json) [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json) --- Document: errors/index Canonical URL: https://marionettejs.com/errors/ Markdown URL: https://marionettejs.com/errors/index.md Reading SHA-256: 6ed6699baacdaa830950596305c8e41b4b15d62a6aac7a180e50abb15a5abd4a # Diagnostic codes - [MN0001: view el must be dom element](/errors/MN0001.md): retired - [MN0002: region el type invalid](/errors/MN0002.md): retired - [MN0003: view already owned](/errors/MN0003.md): active - [MN0004: region el required](/errors/MN0004.md): active - [MN0005: region el not found](/errors/MN0005.md): active - [MN0006: region view required](/errors/MN0006.md): retired - [MN0007: region view destroyed](/errors/MN0007.md): active - [MN0008: region definition invalid](/errors/MN0008.md): retired - [MN0009: event bindings invalid](/errors/MN0009.md): retired - [MN0010: request bindings invalid](/errors/MN0010.md): retired - [MN0011: collection view child view required](/errors/MN0011.md): active - [MN0012: collection view child view invalid](/errors/MN0012.md): retired - [MN0013: collection view container not found](/errors/MN0013.md): active - [MN0014: collection view filter invalid](/errors/MN0014.md): retired - [MN0015: collection view swap non children](/errors/MN0015.md): active - [MN0016: behavior definition invalid](/errors/MN0016.md): retired - [MN0017: radio channel name required](/errors/MN0017.md): active - [MN0018: ui reference invalid](/errors/MN0018.md): active - [MN0019: handler not callable](/errors/MN0019.md): active - [MN0020: named region not found](/errors/MN0020.md): active - [MN0021: radio channel not found](/errors/MN0021.md): active - [MN0022: collection view empty view invalid](/errors/MN0022.md): retired - [MN0023: ui elements unavailable](/errors/MN0023.md): active - [MN0024: child container argument invalid](/errors/MN0024.md): active - [MN0025: child container method not callable](/errors/MN0025.md): retired - [MN0026: entity event name unsafe](/errors/MN0026.md): active - [MN0027: feature name invalid](/errors/MN0027.md): retired - [MN0028: region destroyed operation](/errors/MN0028.md): retired - [MN0029: view destroyed set element](/errors/MN0029.md): retired - [MN0030: region registration conflict](/errors/MN0030.md): active - [MN0031: application registration conflict](/errors/MN0031.md): active - [MN0032: region name invalid](/errors/MN0032.md): active - [MN0033: merge options keys invalid](/errors/MN0033.md): retired - [MN0034: state key invalid](/errors/MN0034.md): retired - [MN0035: state ownership conflict](/errors/MN0035.md): retired - [MN0036: event delegator contract invalid](/errors/MN0036.md): retired - [MN0037: adapter observation unsupported](/errors/MN0037.md): active - [MN0038: adapter cleanup invalid](/errors/MN0038.md): retired - [MN0039: collection data contract invalid](/errors/MN0039.md): active [Canonical source](/docs/markdown/config/diagnostics/catalog.json) · [Source identity](/docs/manifest.json)