Skip to content

Subscription Declarations

Shane Brinkman-Davis edited this page Jan 2, 2017 · 1 revision

@subscriptions takes an object as input with each entry describing one subscription.

A subscription consists of 3 parts:

  • stateField: the field in @state which will be set with the subscribed-to data
  • model: the subscribed-to model (from the ModelRegistry)
  • key: key for the specific, subscribed-to data in the model

There are many different ways to define the subscription, shown below.

Subscription Declarations, Object Forms

Fully Explicit

  @subscriptions
    stateField:
      model: "modelName", model-instance or (props) -> "modelName"
      key:   "key",       key-object     or (props) -> "key" or key-object

Model-name == StateField-name with Explicit, Constant Key

@subscriptions
  stateField: constantKey

is equivalent to:

@subscriptions
  stateField:
    model:  'stateField'
    key:    constantKey

Model-name == StateField-name with Key-Function

@subscriptions
  stateField: (props) -> # return key

is equivalent to:

@subscriptions
  stateField:
    model:  'stateField'
    key:    (props) -> # return key

Example:

@subscriptions
  user: (props) -> props.userId

# Or, using coffeescript shorthand:
@subscriptions
  user: ({userId}) -> userId

Subscription Declarations, String Forms

In addition to declaring subscriptions with object-notation, you can also use a simple string for common subscription-types. A subscription-string can contain one or more subscription declarations separated by spaces or commas.

Model Form

This form is useful for subscribing to a single record from a table. This pattern works best if you follow the Flux Conventions.

@subscriptions "myField"

is equivalent to:

@subscriptions
  myField:
    model:  'myField'
    key:    ({myField, myFieldId}) -> myField?.id || myFieldId

Example:

@subscriptions "post"

#is short for:
@subscriptions
  post:
    model:  "post"
    key:    ({post, postId}) -> post?.id || postId

Model.Key form

This form is useful for subscribing to a specific, known key. In particularly, this works well with ApplicationState models.

@subscriptions "modelName.fieldName"

is equivalent to:

@subscriptions
  fieldName:
    key: fieldName
    model: modelName

Key functions

If the key or model is a function, the function:

  • is executed without @ set
  • inputs: (props) - the component
  • outputs: key or modelName respectively
###
IN: props is the component instance's @props
@/THIS: not set
OUT: key
###
(props) -> key

Key-functions are called initially during getInitialState to set up initial subscriptions.

If the key-function returns null, all dependent state fields will be set to null. No other action will be taken.

Whenever @props changes (e.g. when componentWillReceiveProps is called), these key-functions are re-evaluated. If the return value changes, subscriptions are updated and new data is requested where needed.