MCPcopy Index your code
hub / github.com/Squareknot/marionette.state

github.com/Squareknot/marionette.state @v1.0.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.0.1 ↗ · + Follow
35 symbols 49 edges 9 files 0 documented · 0%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

marionette.state

One-way state architecture for a Marionette.js app.

Build Status Test Coverage Code Climate Dependency Status

Installation

npm install marionette.state
bower install marionette-state
git clone git://github.com/Squareknot/marionette.state.git

Documentation

Reasoning

A Marionette View is a DOM representation of a Backbone model. When the model updates, so does the view. Here is a quick example:

// Region to attach views
var region = new Mn.Region({ el: '#region' });

// Model synced with '/rest-endpoint'
var model = new Backbone.Model({ url: '/rest-endpoint' });

// View will re-render when the model changes
var View = Mn.ItemView.extend({
  modelEvents: {
    'change': 'render'
  }
});

// Create the view
var view = new View({ model: model });

// Fetch the latest data
model.fetch().done(() => {
  // Show the view with initial data
  region.show(view);
});

// Updating the model later will cause the view to re-render.
model.fetch();

This is great for views that are only interested in representing simple content. Consider more complex, yet quite common, scenarios:

  • A view renders core content but also reacts to user interaction. E.g., a view renders a list of people, but the end user is able to select individal items with a "highlight" effect before saving changes.
  • A view renders core content but also depends on external state. E.g., a view renders a person's profile, but if the profile belongs to the authenticated user then enable "edit" features.
  • Multiple views share a core content model but each have unique view states. E.g., multiple views render a user profile object, but in completely different ways that require unique view states: an avatar beside a comment, a short bio available when hovering over an avatar, a full user profile display.

Common solutions:

  • Store view states in the core content model, but override toJSON to avoid sending those attributes to the server.
  • Store view states in the core content model shared between views, but avoid naming collisions or other confusion (which view is "enabled"?).
  • Store view states directly on the view object and follow each "set" with "if different" statements so you know when a state has changed.

Each of these solutions works up until a point, but side effects mount as complexity rises: Logic-heavy views, views unreliably reflecting state changes, models doing too much leading to excessive re-renders, accidentally transmitting state data to server on save.

Separating state into its own entity and then maintaining that entity with one-way data binding solves each of these problems without the side effects of other solutions. It is a pattern simple enough to implement using pure Marionette code, but this library seeks to simplify the implementation further by providing a state toolset.

Mn.State allows a view to seamlessly depend on any source of state while keeping state logic self-contained and eliminates the temptation to pollute core content models with view-specific state. Best of all, Mn.State does this by providing declarative and expressive tools rather than over-engineering for every use case, much like the Marionette library itself.

Examples

In each of these examples, views are demonstrated without core content models for simplicity. This emphasizes that state management is occurring independently from renderable core content. Adding core content models should be familiar to any Marionette developer.

Stateful View

From time to time, a view needs to support interactions that only affect itself. On refresh, these states are reset. In this example, a transient view spawns it own, also transient, State.

State flow for a simple interactive view:

  1. A view is rendered with some initial state.
  2. The user interacts with the view, triggering a state change.
  3. The view reacts by updating the DOM according to the new state.

Solved with Mn.State:

  1. View renders initial View State.
  2. View triggers events that are handled by View State.
  3. View State reacts to view events, updating its attributes.
  4. View reacts to state changes, updating the DOM.
// Listens to view events and updates view state attributes.
var ToggleState = Mn.State.extend({
  defaultState: {
    active: false
  },

  componentEvents: {
    'toggle': 'onToggle'
  },

  onToggle() {
    var active = this.get('active');
    this.set('active', !active);
  }
});

// A toggle button that is alternately "active" or not.
var ToggleView = Mn.ItemView.extend({
  template: 'Toggle Me',
  tagName: 'button',

  triggers: {
    'click .js-toggle': 'toggle'
  },

  stateEvents: {
    'change:active': 'onChangeActive'
  },

  // Create and sync with my own State.
  initialize() {
    this.state = new ToggleState({ component: this });
    Mn.State.syncEntityEvents(this, this.state, this.stateEvents, 'render');
  },

  // Active class will be added/removed on render and on 'active' change.
  onChangeActive(state, active) {
    if (active) {
      this.$el.addClass('is-active');
    } else {
      this.$el.removeClass('is-active');
    }
  }
});

var toggleView = new ToggleView();

var appRegion = new Mn.Region({ el: '#app-region' });
appRegion.show(toggleView);

View Directly Dependent upon Application State

Relatively often, it is convenient for a view to depend on long-lived application state. This example uses authentication status to demonstrate binding a view directly to the state of the application.

State flow for a simple view that depends directly upon long-lived application state:

  1. A view is rendered with current app state.
  2. The view triggers an app-level event, resulting in an app state change.
  3. The view reacts to app state changes, updating the DOM.

Solved with Mn.State:

  1. View renders initial App State.
  2. View trigger events that are handled by App State.
  3. App State reacts to events, updating its attributes.
  4. View reacts to App State changes, updating the DOM.
// Listens to application level events and updates app State attributes.
var AppState = Mn.State.extend({
  defaultState: {
    authenticated: false
  },

  componentEvents: {
    'login': 'onLogin',
    'logout': 'onLogout'
  },

  onLogin() {
    this.set('authenticated', true);
  },

  onLogout() {
    this.set('authenticated', false);
  }
});

// Alternately a login or logout button depending on app authentication state.
var ToggleAuthView = Mn.ItemView.extend({
  template: 'This Button Label Will Be Replaced',
  tagName: 'button',

  triggers: {
    'click': 'loginLogout'
  },

  appStateEvents: {
    'change:authenticated': 'onChangeAuthenticated'
  },

  // Bind to app State.
  initialize(options={}) {
    this.appState = options.appState;
    this.appChannel = Radio.channel('app');
    Mn.State.syncEntityEvents(this, this.appState, this.appStateEvents, 'render');
  },

  // Button text will be updated on every render and `action` change.
  onChangeAuthenticated(appState, authenticated) {
    if (authenticated) {
      this.$el.text('Logout');
    } else {
      this.$el.text('Login');
    }
  },

  // Login/logout toggle will always fire the appropriate action.
  loginLogout() {
    if (this.appState.get('authenticated')) {
      Radio.trigger('app', 'logout');
    } else {
      Radio.request('app', 'login');
    }
  }
});

var appChannel = Radio.channel('app');
var appState = new AppState({ component: appChannel });
var toggleAuthView = new ToggleAuthView({ appState: appState });

var appRegion = new Mn.Region({ el: '#app-region' });
appRegion.show(toggleAuthView);

View Indirectly Dependent upon Application State

Sometimes a view has its own, transient, internal state that is related to long-lived application state. While this particular example doesn't require that layer of indirection to achieve its goal (a Login/Logout button), the goal here is to demonstrate all that is necessary to achieve two tiers of State.

State flow for a simple view that depends indirectly on long-lived application state:

  1. View is rendered with initial state dependent upon current app state.
  2. View triggers an app-level event, resulting in an app state change.
  3. App state change results in a view state change.
  4. View reacts to view state changes, updating the DOM.

Solved with Mn.State:

  1. View State synchronizes with App State.
  2. View renders initial View State.
  3. View triggers events that are handled by App State.
  4. App State reacts to events, updating its attributes.
  5. View State reacts to App State changes, updating its attributes.
  6. View reacts to View State changes, updating the DOM.
// Listens to application level events and updates state attributes.
var AppState = Mn.State.extend({
  defaultState: {
    authenticated: false
  },

  componentEvents: {
    'login': 'onLogin',
    'logout': 'onLogout'
  },

  onLogin() {
    this.set('authenticated', true);
  },

  onLogout() {
    this.set('authenticated', false);
  }
});

// Syncs with application State.
var ToggleAuthState = Mn.State.extend({
  defaultState: {
    action: 'login'
  },

  appStateEvents: {
    'change:authenticated': 'onChangeAuthenticated'
  },

  initialize(options={}) {
    this.appState = options.appState;
    this.syncEntityEvents(this.appState, this.appStateEvents);
  },

  // Called on initialize and on change app 'authenticated'.
  onChangeAuthenticated(appState, authenticated) {
    if (authenticated) {
      this.set('action', 'logout');
    } else {
      this.set('action', 'login');
    }
  }
});

// Alternately a login or logout button depending on app authentication state.
var ToggleAuthView = Mn.ItemView.extend({
  template: 'This Button Label Will Be Replaced',
  tagName: 'button',

  triggers: {
    'click': 'loginLogout'
  },

  stateEvents: {
    'change:action': 'onChangeAction'
  },

  // Create and bind to my own State, which is injected with app State.
  initialize(options={}) {
    this.appChannel = Radio.channel('app');
    this.state = new ToggleAuthState({
      appState: options.appState,
      component: this
    });
    Mn.State.syncEntityEvents(this, this.state, this.stateEvents, 'render');
  },

  // Button text will be updated on every render and 'action' change.
  onChangeAction(state, action) {
    this.$el.text(action);
  },

  // Login/logout toggle will always fire the appropriate action.
  loginLogout() {
    this.appChannel.trigger(this.state.get('action'));
  }
});

var appChannel = Radio.channel('app');
var appState = new AppState({ component: appChannel });
var toggleAuthView = new ToggleAuthView({ appState: appState });

var appRegion = new Mn.Region({ el: '#app-region' });
appRegion.show(toggleAuthView);

View Indirectly Dependent upon Application State with Business Service

An application with a business layer for handling persistence to a server is just one more step--the addition of an app controller that responds to Radio requests.

State flow for a simple view that depends indirectly on long-lived application state connected to a business service:

  1. View is rendered with initial state dependent upon current app state.
  2. View makes an app-level request, affecting business objects and resulting in an app state change.
  3. App state change results in a view state change.
  4. View reacts to view state changes, updating the DOM.

Solved with Mn.State:

  1. View State synchronizes with App State.
  2. View renders initial View State.
  3. View makes requests that are handled by App Controller.
  4. App Controller modifies business objects and triggers app events.
  5. App State reacts to app events, updating its attributes.
  6. View State reacts to App State changes, updating its attributes.
  7. View reacts to View State changes, updating the DOM.

```js // Listens to application level events and updates state attributes. var AppState = Mn.State.extend({ defaultState: { authenticated: false },

componentEvents: { 'login': 'onLogin', 'logout': 'onLogout' },

onLogin() { this.set('authenticated', true); },

onLogout() { this.set('authenticated', false); } });

// App controller fields application level requests and t

Core symbols most depended-on inside this repo

stop
called by 3
src/state.functions.js
createLintTask
called by 2
gulpfile.js
syncBinding
called by 1
src/state.functions.js
sync
called by 1
src/state.functions.js
_when
called by 1
src/state.functions.js
_now
called by 1
src/state.functions.js
jscsNotify
called by 0
gulpfile.js
constructor
called by 0
src/state.functions.js

Shape

Function 29
Method 4
Class 2

Languages

TypeScript100%

Modules by API surface

src/state.js16 symbols
src/state.functions.js10 symbols
test/spec/state.functions.spec.js5 symbols
gulpfile.js3 symbols
test/spec/state.spec.js1 symbols

For agents

$ claude mcp add marionette.state \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact