All Projects → mmlpxjs → Mmlpx

mmlpxjs / Mmlpx

Licence: mit
🐘 mobx model layer paradigm

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Mmlpx

Thirtyinch
a MVP library for Android favoring a stateful Presenter
Stars: ✭ 1,052 (+541.46%)
Mutual labels:  architecture, mvvm
Xaml Code Experiences
A collection of the experiences I have collected during days of Xamarin and Wpf, while following the MVVM design pattern.
Stars: ✭ 114 (-30.49%)
Mutual labels:  architecture, mvvm
Swift Design Patterns
🚀 The ultimate collection of various Software Design Patterns implemented in Swift [Swift 5.0, 28 Patterns].
Stars: ✭ 85 (-48.17%)
Mutual labels:  architecture, mvvm
Karchi
Repository that showcases 3 different Android app architectures, all with Java and Kotlin versions: "Standard Android", MVP and MVVM. The exact same app is built 6 times following the different patterns.
Stars: ✭ 20 (-87.8%)
Mutual labels:  architecture, mvvm
Restapimvvm
App that interacts with a Rest Api. Architecture is MVVM.
Stars: ✭ 130 (-20.73%)
Mutual labels:  architecture, mvvm
Mvvmc Splitviewcontroller
Example project with UITabBarController inside UISplitViewController using RxSwift and MVVM-C architecture.
Stars: ✭ 45 (-72.56%)
Mutual labels:  architecture, mvvm
Ios Architectures
Sample app for iOS architectures
Stars: ✭ 90 (-45.12%)
Mutual labels:  architecture, mvvm
Ribs
Uber's cross-platform mobile architecture framework.
Stars: ✭ 6,641 (+3949.39%)
Mutual labels:  architecture, mvvm
Android Mvvm Architecture
A basic sample android application to understand MVVM in a very simple way.
Stars: ✭ 129 (-21.34%)
Mutual labels:  architecture, mvvm
Androidarchitecture
Android Architecture using Google guides
Stars: ✭ 127 (-22.56%)
Mutual labels:  architecture, mvvm
Ios Architecture
A collection of iOS architectures - MVC, MVVM, MVVM+RxSwift, VIPER, RIBs and many others
Stars: ✭ 901 (+449.39%)
Mutual labels:  architecture, mvvm
Mvvmarchitecture
MVVM 框架,采用 Kotlin+Jetpack,可自由配置功能,欢迎 star,fork,issue
Stars: ✭ 159 (-3.05%)
Mutual labels:  architecture, mvvm
Androidviewmodel
Separating data and state handling from Fragments or Activities without lots of boilerplate-code.
Stars: ✭ 824 (+402.44%)
Mutual labels:  architecture, mvvm
Sesame
Android architecture components made right
Stars: ✭ 48 (-70.73%)
Mutual labels:  architecture, mvvm
Ios Clean Architecture Mvvm
Template iOS app using Clean Architecture and MVVM. Includes DIContainer, FlowCoordinator, DTO, Response Caching and one of the views in SwiftUI
Stars: ✭ 753 (+359.15%)
Mutual labels:  architecture, mvvm
Alfonz
Mr. Alfonz is here to help you build your Android app, make the development process easier and avoid boilerplate code.
Stars: ✭ 90 (-45.12%)
Mutual labels:  architecture, mvvm
Android Showcase
💎 Android application following best practices: Kotlin, Coroutines, JetPack, Clean Architecture, Feature Modules, Tests, MVVM, DI, Static Analysis...
Stars: ✭ 5,214 (+3079.27%)
Mutual labels:  architecture, mvvm
Mobx State Tree
Full-featured reactive state management without the boilerplate
Stars: ✭ 6,317 (+3751.83%)
Mutual labels:  snapshot, mobx
Ios Design Patterns
Learning ground for iOS Design Pattern included with sample projects for MVC, MVP, MVVM, and VIPER
Stars: ✭ 120 (-26.83%)
Mutual labels:  architecture, mvvm
Cocktailapp
Cocktails Android App with Clean Architecture, MVVM , Retrofit, Coroutines, Navigation Components , Room, Dagger Hilt, Cache Strategy and Coroutines Flow
Stars: ✭ 128 (-21.95%)
Mutual labels:  architecture, mvvm

mmlpx

npm version coverage npm downloads Build Status

mmlpx is an abbreviation of mobx model layer paradigm, inspired by CQRS and Android Architecture Components, aims to provide a mobx-based generic layered architecture for single page application.

undefiend

Installation

npm i mmlpx -S

or

yarn add mmlpx

Requirements

  • MobX: ^3.2.1 || ^4.0.0 || ^5.0.0

Boilerplates

Motivation

Try to explore the possibilities for building a view-framework-free data layer based on mobx, summarize the generic model layer paradigm, and provide the relevant useful toolkits to make it easier and more intuitive.

Articles

Features

import { inject, onSnapshot, getSnapshot, applySnapshot } from 'mmlpx'
import Store from './Store'

@observer
class App extends Component {
  
  @inject() store: Store
  
  stack: any[]
  cursor = 0
  disposer: IReactionDisposer
  
  componentDidMount() {
    this.stack.push(getSnapshot());
    this.disposer = onSnapshot(snapshot => {
      this.stack.push(snapshot)
      this.cursor = this.stack.length - 1
      this.store.saveSnapshot(snapshot)
    })
  }
    
  componentWillUmount() {
    this.disposer();
  }
  
  redo() {
    applySnapshot(this.stack[++this.cursor])
  }
  
  undo() {
    applySnapshot(this.stack[--this.cursor])
  }
}

DI System

It is well known that MobX is an value-based reactive system which lean to oop paradigm, and we defined our states with a class facade usually. To avoid constructing the instance everytime we used and to enjoy the other benifit (unit test and so on), a di system is the spontaneous choice.

mmlpx DI system was deep inspired by spring ioc.

Typescript Usage

import { inject, ViewModel, Store } from 'mmlpx';

@Store
class UserStore {}

@ViewModel
class AppViewModel {
    @inject() userStore: UserStore;
}

Due to we leverage the metadata description ability of typescript, you need to make sure that you had configured emitDecoratorMetadata: true in your tsconfig.json.

Javascript Usage

import { inject, ViewModel, Store } from 'mmlpx';

@Store
class UserStore {}

@ViewModel
class AppViewModel {
    @inject(UserStore) userStore;
}

More Advanced

inject

Sometimes you may need to intialize your dependencies dynamically, such as the constructor parameters came from router query string. Fortunately mmlpx supported the ability via inject.

import { inject, ViewModel } from 'mmlpx'

@ViewModel
class ViewModel {
    @observable.ref
    user = {};
    
    constructor(projectId, userId) {
        this.projectId = projectId;
        this.userId = userId;
    }
    
    loadUser() {
        this.user = this.http.get(`/projects/${projectId}/users/${userId}`);
    }
}

class App extends Component {
    @inject(ViewModel, app => [app.props.params.projectId, app.props.params.userId])
    viewModel;
    
    componentDidMount() {
        this.viewModel.loadUser();
    }
}

inject decorator support four recipes initilizaztion:

  • inject() viewModel: ViewModel; only for typescript.
  • inject(ViewModel) viewModel; generic usage.
  • inject(ViewModel, 10, 'kuitos') viewModel; initialized with static parameters for ViewModel constrcutor.
  • inject(ViewModel, instance => instance.router.props) viewModel; initialized with dynamic instance props for ViewModel constructor.

Notice that all the Store decorated classes are singleton by default so that the dynamic initial params injection would be ignored by di system, if you wanna make your state live around the component lifecycle, always decorated them with ViewModel decorator.

instantiate

While you are limited to use decorator in some scenario, you could use instantiate to instead of @inject.

@ViewModel
class UserViewModel {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

const userVM = instantiate(UserViewModel, 'kuitos', 18);

Test Support

mmlpx di system also provided the mock method to support unit test.

  • function mock<T>(Clazz: IMmlpx<T>, mockInstance: T, name?: string) : recover
@Store
class InjectedStore {
    name = 'kuitos';
}

class ViewModel {
    @inject() store: InjectedStore;
}

// mock the InjectedStore
const recover = mock(InjectedStore, { name: 'mock'});

const vm = new ViewModel();
expect(vm.store.name).toBe('mock');
// recover the di system
recover();

const vm2 = new ViewModel();
expect(vm2.store.name).toBe('kuitos');

Strict Mode

If you wanna strictly follow the CQRS paradigm to make your state changes more predictable, you could enable the strict mode by invoking useStrcit(true), then your actions in Store or ViewModel will throw an exception while you declaring a return statement.

import { useStrict } from 'mmlpx';
useStrict(true);

@Store
class UserStore {
    @observable name = 'kuitos';
    
    @action updateName(newName: string) {
        this.name = newName;
        // return statement will throw a exceptin when strict mode enabled
        return this.name;
    }   
}

Time Travelling

Benefit from the power of model management by di system, mmlpx supported time travelling out of box.

All you need are the three apis: getSnapshot, applySnapshot and onSnapshot.

  • function getSnapshot(injector?: Injector): Snapshot;

    function getSnapshot(modelName: string, injector?: Injector): Snapshot;

  • function applySnapshot(snapshot: Snapshot, injector?: Injector): void;

  • function onSnapshot(onChange: (snapshot: Snapshot) => void, injector?: Injector): IReactionDisposer; function onSnapshot(modelName: string, onChange: (snapshot: Snapshot) => void, injector?: Injector): IReactionDisposer;

That's to say, mmlpx makes mobx do HMR and SSR possible as well!

As we need to serialize the stores to persistent object, and active stores with deserialized json, we should give a name to our Store:

@Store('UserStore')
class UserStore {}

Fortunately mmlpx had provided ts-plugin-mmlpx to generate store name automatically, you don't need to name your stores manually.

You can check the mmlpx-todomvc redo/undo demo and the demo source code for details.

Layered Architecture Overview

Store

Business logic and rules definition, equate to the model in mvvm architecture, singleton in an application. Also known as domain object in DDD, always represent the single source of truth of the application.

import { observable, action, observe } from 'mobx';
import { Store, inject } from 'mmlpx';
import UserLoader from './UserLoader';

@Store
class UserStore {
    
    @inject() loader: UserLoader;
    
    @observable users: User[];
    
    @action
    async loadUsers() {
        const users = await this.loader.getUsers();
        this.users = users;
    }
    
    @postConstruct
    onInit() {
        observe(this, 'users', () => {})
    }
}

Method decorated by postConstruct will be invoked when Store initialized by DI system.

ViewModel

Page interaction logic definition, live around the component lifecycle, ViewModel instance can not be stored in ioc container.

The only direct consumer of Store, besides the UI-domain/local states, others are derived from Store via @computed in ViewModel.

The global states mutation are resulted by store command invocation in ViewModel, and the separated queries are represented by transparent subscriptions with computed decorator.

import { observable, action } from 'mobx';
import { postConstruct, ViewModel, inject } from 'mmlpx';

@ViewModel
class AppViewModel {
    
    @inject() userStore: UserStore;
    
    @observable loading = true;
    
    @computed
    get userNames() {
        return this.userStore.users.map(user => user.name);
    }
    
    @action
    setLoading(loading: boolean) {
        this.loading = loading;
    }   
}

Loader

Data accessor for remote or local data fetching, converting the data structure to match definited models.

class UserLoader {
    async getUsers() {
        const users = await this.http.get<User[]>('/users');
        return users.map(user => ({
            name: user.userName,
            age: user.userAge,
        }))
    }
}

Component

export default App extends Component {
    
    @inject()
    vm: AppViewModel;
    
    render() {
        const { loading, userName } = this.vm;
        return (
            <div>
                {loading ? <Loading/> : <p>{userName}</p>} 
            </div>
        );
    }
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].