optimizely / nuclear-js

Reactive Flux built with ImmutableJS data structures. Framework agnostic.

Home Page:https://optimizely.github.io/nuclear-js/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Calling a Getter with parameters

ccapndave opened this issue · comments

Is there a solution for this use case?

If a getter needs to be dynamic then it should be composed of another getter that represents the parameter as state in the system.

For example, imagine we have a store mantaining the state of a map of id => ListItem, and a store maintaining the currently selected item id.

var selectedItemGetter = [
  ['listItems'],
  ['selectedItemId'],
  function(items, id) {
    return items.get(id)
  }
]

The idea of using getters is it provides a unit of immediate evaluation for some state in the system. Another way to think about a Getter is it represents a question, in our case "What is the currently selected item?" We can get the answer to that question immediately via flux.evaluate(selectedItemGetter) or get notified whenever the answer changes via flux.observe(selectedItemGetter, handlerFn)

If you want to create a function that evaluates a getter based on the parameters it would look like:

function getItem(id) {
  return flux.evaluate([
    ['items'],
    function(items) { 
      return items.get(id)
    }
  ])
}

Could you just use a function to create a getter? I suppose the parameter would reasonably need to be constant for the lifetime of the component where getter is bound

function getItem(id) {
  return [
    ['items'],
    function(items) { 
      return items.get(id)
    }
  ]
}

@jordangarcia In your getItem() example, where do you imagine that living? In actions.js? It seems like a fundamental requirement of a getter is that it is an array, so even though this is technically gets data, it seems like it cannot go there since it doesn't fit into the prescribed pattern. The only other place I can see it logically going is actions, (or even maybe index), however I wanted to get your perspective. Thanks.

It should live in your getters.js as it is related to getters.