observable

对事件进行观察

  1. class Event {
  2. constructor() {
  3. this.handlers = new Map();
  4. this.count = 0;
  5. }
  6. subscribe(handler) {
  7. this.handlers.set(++this.count, handler);
  8. return this.count;
  9. }
  10. unsubscribe(idx) {
  11. this.handlers.delete(idx);
  12. }
  13. // 1. 谁触发这个事件
  14. // 2. 额外的信息(事件参数)
  15. fire(sender, args) {
  16. this.handlers.forEach((handler) => {
  17. handler(sender, args);
  18. });
  19. }
  20. }
  21. class FallsIllArgs {
  22. constructor(address) {
  23. this.address = address;
  24. }
  25. }
  26. class Person {
  27. constructor(name, address) {
  28. this.name = name;
  29. this.address = address;
  30. this.fallsIll= new Event();
  31. }
  32. catchCold() {
  33. this.fallsIll.fire(this, new FallsIllArgs(this.address));
  34. }
  35. }
  36. let person = new Person('张三', '游泳池');
  37. let sub = person.fallsIll.subscribe((sender, args) => {
  38. console.log(`${sender.name}需要医生前往${args.address}`);
  39. })
  40. person.catchCold();
  41. person.fallsIll.unsubscribe(sub);
  42. person.catchCold();

对属性进行观察

  1. class Event {
  2. constructor() {
  3. this.handlers = new Map();
  4. this.count = 0;
  5. }
  6. subscribe(handler) {
  7. this.handlers.set(++this.count, handler);
  8. return this.count;
  9. }
  10. unsubscribe(idx) {
  11. this.handlers.delete(idx);
  12. }
  13. fire(sender, args) {
  14. this.handlers.forEach((handler) => {
  15. handler(sender, args);
  16. });
  17. }
  18. }
  19. class PropertyChangedArgs {
  20. constructor(name, newValue) {
  21. this.name = name;
  22. this.newValue = newValue;
  23. }
  24. }
  25. class Person {
  26. constructor(age) {
  27. this._age = age;
  28. this.propertyChanged = new Event();
  29. }
  30. get age() {
  31. return this._age;
  32. }
  33. set age(value) {
  34. if (!value || this._age === value) {
  35. return;
  36. }
  37. this._age = value;
  38. this.propertyChanged.fire(this, new PropertyChangedArgs('age', value));
  39. }
  40. }
  41. class RegistrationChecker {
  42. constructor(person) {
  43. this.person = person;
  44. this.token = person.propertyChanged.subscribe(this.handleAgeChanged);
  45. }
  46. handleAgeChanged = (sender, args) => {
  47. console.log(args.name === 'arg');
  48. if (sender === this.person && args.name === 'age') {
  49. if (args.newValue < 18) {
  50. console.log(`很抱歉,您现在年龄还太小了,不能够注册`);
  51. } else {
  52. console.log(`现在可以开始注册了!`);
  53. sender.propertyChanged.unsubscribe(this.token);
  54. }
  55. }
  56. }
  57. }
  58. let person = new Person('Tom');
  59. let checker = new RegistrationChecker(person);
  60. for (let i = 15; i < 22; i++) {
  61. console.log(`年龄变到了${i}`);
  62. person.age = i;
  63. }