mediawiki-extensions-Popups/docs/change_listener.md
Thiemo Kreuz b28f48d6d6 Rename variables in change listeners for clarity
This patch does nothing but rename a pair of variables:
"prevState/state" becomes "oldState/newState". Reasoning:

1. The abbreviated "prev" is confusing, especially because we
are in a codebase that is all about "previews".

2. We are in a context that is all about a state **change**.
Change listeners get notified about the change from one state
to another. While it would be possible to stick to the already
mentioned "previous/current" terminology, I find the word
"current" confusing. What is "current" in this context? Did
the state already change? Am I notified about a change that is
**going** to happen or already happened? Is this even relevant?
I don't think it is. Therefor "old/new".

Another possibility is "previous/next".

Change-Id: Id886e1a095967fe86fb9021f59e335c62da8994e
2021-04-15 10:19:40 +02:00

1.3 KiB

Change Listeners

Redux's Store#subscribe allows you to subscribe to updates to the state tree. These updates are delivered every time an action is dispatched to the store, which may or may not result in a change of state.

In the Extension:Popups codebase, a change listener is a function that is only called when the state tree has changed. As such, change listeners are predominantly responsible for updating the UI so that it matches the state in the store.

Registering Change Listeners

Change listeners are registered automatically during boot in the registerChangeListeners function. It expects the values of the mw.popups.changeListeners map to be factory functions that accept, currently, the bound action creators, i.e.

mw.popups.changeListeners.foo = function ( boundActions ) {
  var $link = $( '<a>' )
    .attr( 'href', '#' )
    .click( boundActions.showSettings );

  return function ( oldState, newState ) {
    // ...
  }
};

You'll note that the above change listener is effectful and maintains some local state ($link), both of which are acceptable. The former is unavoidable and the latter is to avoid populating the state tree with unimportant data.