简体   繁体   中英

What do you call a pattern that uses a eventBus to interact with all its components ( Slides / Dots / Arrows )

I have been playing around for a while with the code of glide.js and have been quite facinated by the design pattern used in Glide.js, that looks something like below, below is just the edited gist of the code, but i really have never seen something quite like this:-

The full code can be found HERE .

import defaults from './defaults'
import { warn } from './utils/log'
import { mount } from './core/index'
import { mergeOptions } from './utils/object'
import { toInt, isObject, isArray } from './utils/unit'

import EventsBus from './core/event/events-bus'

export default class Glide {
  /**
   * Construct glide.
   *
   * @param  {String} selector
   * @param  {Object} options
   */
  constructor (selector, options = {}) {
    this._c = {}
    this._t = []
    this._e = new EventsBus()

    this.disabled = false
    this.selector = selector
    this.settings = mergeOptions(defaults, options)
    this.index = this.settings.startAt
  }

  /**
   * Initializes glide.
   *
   * @param {Object} extensions Collection of extensions to initialize.
   * @return {Glide}
   */
  mount (extensions = {}) {
    this._e.emit('mount.before')

    if (isObject(extensions)) {
      this._c = mount(this, extensions, this._e)
    } else {
      warn('You need to provide a object on `mount()`')
    }

    this._e.emit('mount.after')

    return this
  }
}

Notice how an instance of a eventBus is passed to each component (which can be a Arrow Component, Slider Component, Dots Component) of the slider plugin. This instance of eventBus than is used to communicate between all the components. I have a faint idea of how the pub/sub pattern works in JS. but What exactly is this pattern and what are the advantages of using it?

EventBus pattern mostly used for subscribing/publishing events on top level by maintaining loose coupling principle on your application. The subscribers of publisher never knows the source of it.

It is close to Observer pattern because of publishers and subscribers. But a class which uses EventBus for firing events cannot be named as Observer class . It just contains an implementation of EventBus.

The advantages;

  1. It just simplifies communication between classes.
  2. Also can be useful for centralization of activities like logging, alerts etc.

Depending on the implementation, it may be considered as an Observer pattern , or a Mediator pattern .

This subject was already treated here: Is Eventbus a Mediator or Observer Pattern?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM