react-mvvm
A MVVM pattern for React.
What is it?
React-MVVM is an implementation of the Model-View-ViewModel pattern for React.
It allows you to move virtually all "code-behind" logic from your JSX
component modules, including componentDidMount
and other view functions, into
a ViewModel object. This ViewModel object is then passed as a prop to your JSX.
You can read more about MVVM on Wikipedia.
Install
npm install react-mvvm
or yarn add react-mvvm
Features
- Allows View-first style MVVM, where the View creates its own ViewModel or is passed one by a parent component.
- Allows ViewModel-first with
ViewModel.connect
, a higher-order-component that instantiates the ViewModel and passes it to your component asprops.vm
. - Event-forwarding for view-aware ViewModels with
ViewComponent.forwardEvents
(or inheritingViewComponent
) and theViewAware
base-ViewModel class. - Automatically binds
ViewModel
function properties. (See ViewModel-first example below.) - Coming soon: Redux integration. Put all of your Redux state mapping in your
ViewModel without calling Redux
connect
.
ViewModel-first Example
See the example/
directory for a full example. Summarized below.
The example below only shows one way of exposing a ViewModel to your View.
Define a view that forwards events to a ViewModel and uses the commands provided by the ViewModel.
// file: ./Dashboard.jsximport React from 'react';import MVVM from 'react-mvvm'; ViewComponent { return <div> <h1>Dashboard</h1> <p> Welcome </p> <button => Say Hello </button> <button => Say Goodbye </button> <button => Do Something Else </button> </div> ; } /* constructor(props) { super(props); // You can also just forward events instead of inheriting ViewComponent. ViewComponent.forwardEvents(this, props.vm); } // */
Define the ViewModel.
// file: ./Dashboard.vm.js;; // Functional class properties, automatically passed as view props. { ; }; { ; }; // Prototype methods are NOT passed as view props. { console; } { console; } { console; } // However, if you wish to call a prototype method from the view, // the entire DashboardVM class instance is passed to the view as // `props.vm`. { return { ; }; } ;
API
See: docs/API.md