instance method Spah.State#addExpander
Spah.State#addExpander(expander) → Spah.State
expander (Object): A hash containing the expander properties. Should contain keys (“path” or “paths”) and optionally (“if” or “unless”).
Adds a new expander strategy to this state. Expander strategies are used to flesh out and complete the state in circumstances where the Spah Server is attempting to render HTML for a request given only a partial state with which to do so. See the README for more information on state expanders.
An expander is a hash made up of one or more paths that you want to expand, an optional condition required for the expander to run, and a callback function (all expanders are asynchronous, allowing you to fetch data from a database or other remote source).
Here’s an example expander which, if the user is authenticated, will populate /followers/count with a value.
state.addExpander( {“path”: “/followers/count”, “if”: “/user_authenticated”}, function(queryResult, state, request, expander) { twitterUser.fetchFollowerCount(function(count) { console.log(“setting “+queryResult.path+” to “+ count); queryResult.set(count); expander.done(); } } );
The callback receives queryResult, the SpahQL QueryResult matching the query /followers/count, state, the root-level Spah.State object being expanded, request, the HTTP request, and expander, an object containing methods you’ll use to signal to Spah that this strategy has finished and the next may be started. In the example above, we set the value of /followers/count to some arbitrary value and then call expander.done(), signalling that the expander has completed.
The query or queries specified in path or paths are SpahQL selection queries returning parts of the state for you to modify, while the queries specified in if or unless are SpahQL assertions.
Call state.expand() to run your expanders on-demand for testing or other purposes. Reducers are run in the order in which you added them.
This method returns this state instance so that you may chain addReducer calls.