Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useObservables + model.use pattern #107

Merged
merged 6 commits into from
Jul 16, 2023
Merged

useObservables + model.use pattern #107

merged 6 commits into from
Jul 16, 2023

Conversation

guyca
Copy link
Collaborator

@guyca guyca commented Jul 13, 2023

This PR adds two features that aim to help writing MVVM applications with Obsidian.

useObservers

This hook lets us observe multiple observables with a single method call.

Old New
const [foo] = useObserver(fooObservable);
const [bar] = useObserver(barObservable);
const {foo, bar} = useObservers({ foo: fooObservable, bar: barObservable });

Model base class

In MVVM, data and business logic in encapsulated in classes called "models". The models are made available to the views (typically functional components in React) via useViewModel hooks.

This PR implements an abstract model class that models can extend. It allows developers to easily observe all observables declared in the model using the model.use() method.

Example

  1. Declare a model
import { Model } from 'react-obsidian';

class FooModel extends Model {
  public readonly foo = new Observable(1);
  public readonly bar = new Observable('bar');
}
  1. Expose it via a graph
@Graph()
class FooGraph extends ObjectGraph {
  @Provides()
  fooModel() {
    return new FooModel();
  }
}
  1. Inject the model to a viewModel hook, and use() it
const useFoo = ({ fooModel }: DependenciesOf<FooGraph, 'fooModel'>) => {
    const { foo, bar } = fooModel.use(); // { foo: number, bar: string }
    // Do something useful with foo and bar
  };

const useInjectedFoo = injectHook(useFoo, FooGraph);

@guyca guyca marked this pull request as draft July 13, 2023 19:04
Guy Carmeli added 2 commits July 15, 2023 13:11
The use method returns a useObservables hook that subscribes to all observables in the class that extends the Model.
@guyca guyca marked this pull request as ready for review July 16, 2023 10:41
@guyca guyca merged commit 6dfdb4f into master Jul 16, 2023
@guyca guyca deleted the modelUse branch July 6, 2024 18:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant