项目作者: incetarik

项目描述 :
@when decorator for changing MobX
高级语言: TypeScript
项目地址: git://github.com/incetarik/mobx-when.git
创建时间: 2020-03-09T14:34:58Z
项目社区:https://github.com/incetarik/mobx-when

开源协议:Mozilla Public License 2.0

下载


mobx-when

@when() decorator for changing MobX, especially useful React.Component.

This decorator takes a function to listen changes through computed of MobX. Hence it needs a class having two functions for initializing and deinitializing disposer of the computed. Since this library may be used with React, those are componentDidMount and componentWillUnmount by default. Hence, for React applications, you don’t need to provide any name for the decorator.

This function has global interface declaration called WhenDecorator, which can be used for extending the @when decorator. Usage examples are shown below.

The function decorated will be executed whenever the computed value changes. This enables developer both connecting a function to a changing/computed variable and calling the function manually.

This library utilizes WeakMap to prevent/reduce instance modifications as much as possible.

Example

  1. class UserState {
  2. @observable id?: string
  3. @observable loggedIn = false
  4. @observable comments?: IComment[]
  5. }
  6. const userState = new UserState()
  7. class CommentsView extends React.PureComponent {
  8. @when(() => userState.loggedIn)
  9. loadUserComments() {
  10. // The function here is also bound, hence, `this` refers to CommentsView
  11. // We assume that when user is logged, it gets an ID.
  12. return loadCommentsOf(userState.id)
  13. }
  14. someOtherFunction = () => {
  15. // You can also invoke the function above manually
  16. this.loadUserComments().then(comments => {
  17. userState.comments = comments
  18. })
  19. // ...
  20. console.log('User comments are loading')
  21. // ...
  22. }
  23. }
  24. // Extending example
  25. // Since an interface is given, you can extend the interface to add
  26. // more functionalities to the decorator.
  27. declare global {
  28. interface WhenDecorator {
  29. userLoggedIn(...parameters: any[]): MethodDecorator
  30. }
  31. }
  32. when.userLoggedIn = (...parameters: any[]) => when(() => state.loggedIn, ...parameters)
  33. // Now, we can do
  34. class SomeView extends React.PureComponent {
  35. @when.userLoggedIn()
  36. private reloadUserInformation() {
  37. // ... Reloading user information, since this function will
  38. // automatically be called when user is logged in, we know that
  39. // user is logged in and can use id to load anything related.
  40. // ...
  41. }
  42. }