Me learning react like an absolute chungus
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.1KB

  1. import { action, computed, makeObservable, observable, reaction, when } from "mobx";
  2. let runningID = 0;
  3. class ToDo{
  4. id: number;
  5. @observable
  6. name: string
  7. @observable
  8. isCompleted: boolean;
  9. private disposer: () => void;
  10. constructor( name: string){
  11. makeObservable(this);
  12. this.id = runningID++
  13. this.name = name;
  14. this.isCompleted =false;
  15. this.disposer = reaction(
  16. ()=> this.isCompleted,
  17. ()=> console.log(`${this.name} changed to ${this.isCompleted ? "competed" : "incomplete"}`)
  18. )
  19. }
  20. @action
  21. updateName(newName: string){
  22. this.name = newName;
  23. }
  24. @action
  25. updateCompletion(){
  26. this.isCompleted = !this.isCompleted;
  27. }
  28. dispose(){
  29. this.disposer();
  30. }
  31. }
  32. class ToDoList{
  33. @observable
  34. toDoList: ToDo[] = [];
  35. constructor(){
  36. makeObservable(this);
  37. reaction(
  38. () => this.toDoList.length,
  39. () => {
  40. console.log(
  41. `Total: ${this.toDoList.length}, Completed: ${this.Completed.length} InComplete: ${this.NotCompleted.length}`
  42. );
  43. }
  44. )
  45. when(
  46. () => this.toDoList.length > 10&& this.toDoList.every(toDo => toDo.isCompleted === true),
  47. () => console.log("all tasks are done!")
  48. )
  49. }
  50. @action
  51. addToDo(name: string){
  52. this.toDoList.push(new ToDo(name))
  53. }
  54. @action
  55. removeToDo(name: string){
  56. const toDoToRemove = this.toDoList.find(todo => todo.name === name);
  57. if (toDoToRemove){
  58. toDoToRemove.dispose()
  59. const toDoIndex = this.toDoList.indexOf(toDoToRemove);
  60. this.toDoList.splice(toDoIndex, 1);
  61. }
  62. }
  63. @computed
  64. get Completed(){
  65. return this.toDoList.filter(toDo => toDo.isCompleted === true);
  66. }
  67. @computed
  68. get NotCompleted(){
  69. return this.toDoList.filter(toDo => toDo.isCompleted === false);
  70. }
  71. }
  72. const toDoList = new ToDoList();
  73. toDoList.addToDo("smellson");