观察者模式的一种运用

前端之家收集整理的这篇文章主要介绍了观察者模式的一种运用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

场景

如上图,在一个歌曲详情模块,假设有2个子模块,歌曲模块和评论模块。

在歌曲模块和评论模块中都有评论数量这个属性,当用户评论模块发布了一条评论后,评论模块和歌曲模块的数量要同步更新。

评论模块的数量很好更新,歌曲模块的评论数量怎么同步更新呢?

下面介绍几种实现方法
1. 双向绑定实现

思路:

在AppComponent将评论数量count作为输入参数(@Input)传递给CommentComponent和MusicComponent,当AppComponent中的评论数量改变时,MucisComponent中的评论数量也会同时改变。
当CommentComponent更新评论数量count时,通过输出参数(@Output)更新AppComponent中的评论数量count,MusicComponent中的评论数量count就会跟着改变了。

AppComponent

  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-root',template: `<div>
  5. <app-music [count]="count"></app-music>
  6. <app-comment [(count)]="count"></app-comment>
  7. </div>`
  8. })
  9. export class AppComponent {
  10. count:number = 0;
  11.  
  12. constructor() {
  13.  
  14. }
  15. }

MusicComponent

  1. import { Component,Input } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-music',template: `<div>
  5. <h3>歌曲模块</h3>
  6. <div>评论数:<strong>{{ count }}</strong></div>
  7. </div>`,styleUrls: ['./music.component.css']
  8. })
  9. export class MusicComponent{
  10. // 评论
  11. @Input()
  12. count:number;
  13.  
  14. constructor() { }
  15.  
  16. }

CommentComponent

  1. import { Component,EventEmitter,Input,Output } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-comment',template: `<div>
  5. <h3>评论</h3>
  6. <div>评论数:<strong>{{ count }}</strong></div>
  7. <div>
  8. <textarea #content></textarea>
  9. </div>
  10. <div>
  11. <button (click)="send(content)">发布</button>
  12. </div>
  13. <ul>
  14. <li *ngFor="let item of comments">
  15. {{ item }}
  16. </li>
  17. </ul>
  18. </div>`
  19. })
  20. export class CommentComponent {
  21. // 评论
  22. @Input()
  23. count:number = 0;
  24.  
  25. // 评论数改变事件
  26. @Output()
  27. countChange:EventEmitter<number> = new EventEmitter<number>();
  28.  
  29. // 评论列表
  30. comments:string [] = [];
  31.  
  32. constructor() { }
  33.  
  34. // 发送评论
  35. send(content) {
  36. if (content.value) {
  37. this.comments.push(content.value);
  38. this.count++;
  39. this.countChange.emit(this.count);
  40. }
  41. }
  42.  
  43. }

2. 观察者模式实现

思路

构建一个观察者对象,观察者对象拥有注册(regist),发布(fire),移除(remove)三个方法。在angular2中可以通过依赖注入注入到CommentComponent和MusicComponent。

在MusicComponent中注册(regist),‘count’ 事件。

用户发送评论时,在CommentComponent中发布(fire),‘count’事件。

构造观察者对象

  1. import { Injectable } from '@angular/core';
  2.  
  3. @Injectable()
  4. export class ObserverService {
  5. /**
  6. * 消息队列
  7. * 用数组保存每一种消息的事件队列,
  8. * eventList['count'] = []
  9. * 注册消息时将事件回调函数push到事件队列
  10. * eventList['count'].push(fn)
  11. * 发布消息时依次执行消息队列中的每一个回调函数
  12. * for(let fn of eventList['count']) {
  13. * fn(data);
  14. * }
  15. */
  16. eventList = {};
  17.  
  18. constructor() {
  19.  
  20. }
  21.  
  22. /**
  23. * 发布消息
  24. * @param name 消息名
  25. * @param data 消息数据
  26. */
  27. fire(name:string,data:any) {
  28. if (this.eventList[name]) {
  29. const fns = this.eventList[name];
  30. for(let fn of fns) {
  31. fn(data);
  32. }
  33. }
  34. }
  35.  
  36. /**
  37. * 注册消息
  38. * @param name
  39. * @param fn
  40. */
  41. regist(name:string,fn:any) {
  42. if (typeof fn === 'function') {
  43. const fns = this.eventList[name];
  44. if (fns) {
  45. fns.push(fn);
  46. } else {
  47. this.eventList[name] = [fn];
  48. }
  49. }
  50. }
  51.  
  52. /**
  53. * 移除消息
  54. * @param name
  55. * @param fn
  56. */
  57. remove(name:string,fn:any) {
  58. const fns = this.eventList[name];
  59. if (fns) {
  60. if ( fn ) {
  61. let i;
  62. for(i = 0; i < fns.length; i++) {
  63. if (fns[i] === fn) {
  64. break;
  65. }
  66. }
  67. if (i < fns.length) {
  68. fns.splice(i,1);
  69. }
  70. } else {
  71. fns.length = 0;
  72. }
  73. }
  74. }
  75. }

AppComponent

  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-root',template: `<div>
  5. <app-music></app-music>
  6. <app-comment></app-comment>
  7. </div>`
  8. })
  9. export class AppComponent {
  10. constructor() {
  11.  
  12. }
  13. }

MusicComponent

  1. import { ObserverService } from '../service/observer.service';
  2. import { Component,styleUrls: ['./music.component.css']
  3. })
  4. export class MusicComponent{
  5. // 评论
  6. count:number;
  7.  
  8. constructor(private observiceService:ObserverService) {
  9. // 注册消息
  10. this.observiceService.regist('count',count => this.count = count);
  11. }
  12.  
  13. }

CommentComponent

  1. import { ObserverService } from '../service/observer.service.2';
  2. import { Component,template: `<div>
  3. <h3>评论</h3>
  4. <div>评论数:<strong>{{ count }}</strong></div>
  5. <div>
  6. <textarea #content></textarea>
  7. </div>
  8. <div>
  9. <button (click)="send(content)">发布</button>
  10. </div>
  11. <ul>
  12. <li *ngFor="let item of comments">
  13. {{ item }}
  14. </li>
  15. </ul>
  16. </div>`
  17. })
  18. export class CommentComponent {
  19. // 评论
  20. count:number = 0;
  21.  
  22. // 评论列表
  23. comments:string [] = [];
  24.  
  25. constructor(private observiceService:ObserverService) { }
  26.  
  27. send(content) {
  28. if (content.value) {
  29. this.comments.push(content.value);
  30. this.count++;
  31. // 发布消息
  32. this.observiceService.fire('count',this.count);
  33. }
  34. }
  35.  
  36. }

3. 使用Rxjs中的Subject实现

subject参考

SubjectService

import { Observable,Subject } from 'rxjs/Rx';
import { Injectable } from '@angular/core';

@Injectable()
export class SubjectService {

  1. count:number = 0;
  2. comment:Subject<number>;
  3.  
  4. constructor() {
  5. this.comment = new Subject<number>();
  6. }

}

AppComponent

  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-root',template: `<div>
  5. <app-music></app-music>
  6. <app-comment></app-comment>
  7. </div>`
  8. })
  9. export class AppComponent {
  10. constructor() {
  11.  
  12. }
  13. }

MusicComponent

  1. import { SubjectService } from '../service/subject.service';
  2. import { Component,styleUrls: ['./music.component.css']
  3. })
  4. export class MusicComponent{
  5. // 评论
  6. count:number;
  7.  
  8. constructor(private subjectService:SubjectService) {
  9. // 注册消息
  10. this.subjectService.comment.subscribe(count => this.count = count);
  11. }
  12.  
  13. }

4. 小结

  • 在使用双向绑定进行多个的模块间的数据传输时,可以看到,当需要传递某个变量时,我们需要在每个模块中构造对应的@Input和@Output,借助父模块来进行传递数据,过程比较繁琐。
    AppComponent

CommentComponent

MusicComponent

  • 采用观察者模式,通过其订阅发布机制,可以简化数据传输的过程,使每个模块独立起来,我们的模块能更加专注于业务代码的编写。
    AppComponent

MusicComponent

CommentComponent

  • 借助Rxjs的Subject,我们能很方便的实现同样的功能

猜你在找的Angularjs相关文章