Skip to main content

Create a ViewModel

Before you create a ViewModel, you need to know what a React component is with reactive/js. A ViewModel can use for many components.

For this example, we will create a React component with a name HelloWorld and a ViewModel with a name HelloWorld.viewModel.

Create a React component

HelloWorld.tsx
import React from 'react';

function HelloWorld(props: any) {
return (
<div>
<h1>Hello World</h1>
<button>Click Me!</button>
</div>
);
}

Create a ViewModel

HelloWorld.viewModel.ts
import {
getViewModel,
viewModel,
ViewModelClass,
ModuleIdentifier,
useDataViewModel,
} from '@lamvd0101/reactive-js';

// ============================
// === Step 1. Create types ===
// ============================

interface DataModel {
// Your data model here
name?: string;
}

interface DataViewModel extends DataModel {
// Your data view model here
// You can know the data the same as the component state
isReady?: boolean;
isClicked?: boolean;
}

// ==========================================
// === Step 2. Create a module identifier ===
// ==========================================

// A module identifier is a unique identifier for a ViewModel.
// You can use a string or a symbol.
const mID = new ModuleIdentifier('HelloWorldViewModel');

// ==================================
// === Step 3. Create a ViewModel ===
// ==================================

// @viewModel is a decorator to create a ViewModel with a module identifier.
// ViewModelClass is a parent class of a ViewModel. It is be required to create a ViewModel.
@viewModel(mID)
class HelloWorldViewModel extends ViewModelClass<DataViewModel> {
// The data the same as the component state. With type is DataViewModel.
data: DataViewModel = {};

// This is a custom method to set the data model from somewhere.
init(data: DataModel) {
this.data = {
...data,
isReady: true,
};
}

// This is a custom method to set isClicked to some value.
setIsClicked(isClicked: boolean) {
this.data.isClicked = isClicked;

if (isClicked) {
// This is a method to trigger the component to re-render.
// The React component only re-render when you call this method.
this.triggerRender();
}
}
}

// ====================================
// === Step 4. Export the ViewModel ===
// ====================================

// useHelloWorldViewModel is a hook to get the DataViewModel from the React component.
// It will connect the ViewModel with the React component.
export const useHelloWorldViewModel = () =>
useDataViewModel<DataViewModel>(mID);

// helloWorldViewModel is the instance of the ViewModel. It the same as the controller.
export const helloWorldViewModel = getViewModel<HelloWorldViewModel>(mID);