Skip to main content

Model

new Model(optionsnullable)

A Model object is used to execute commands against a JSONGraph object. Models can work with a local JSONGraph cache, or it can work with a remote JSONGraph object through a DataSource.

Parameters:
Name & Attributes Type Description
options
nullable
Object

a set of options to customize behavior

Properties
Name & Attributes Type Description
source
nullable
DataSource

a data source to retrieve and manage the JSONGraph

cache
nullable
JSONGraph

initial state of the JSONGraph

maxSize
nullable
number

the maximum size of the cache

collectRatio
nullable
number

the ratio of the maximum size to collect when the maxSize is exceeded

errorSelector
nullable
Model~errorSelector

a function used to translate errors before they are returned

onChange
nullable
Model~onChange

a function called whenever the Model's cache is changed

comparator
nullable
Model~comparator

a function called whenever a value in the Model's cache is about to be replaced with a new value.

Source:
Model.js, line 81

Members

getValue

Get data for a single Path.

Source:
Model.js, line 309
Example
var model = new falcor.Model({source: new falcor.HttpDataSource("/model.json") });

 model.
     getValue('user.name').
     subscribe(function(name) {
         console.log(name);
     });

 // The code above prints "Jim" to the console.

setValue

Set value for a single Path.

Source:
Model.js, line 327
Example
var model = new falcor.Model({source: new falcor.HttpDataSource("/model.json") });

 model.
     setValue('user.name', 'Jim').
     subscribe(function(name) {
         console.log(name);
     });

 // The code above prints "Jim" to the console.

Methods

asDataSource() → {DataSource}

Adapts a Model to the DataSource interface.

Source:
Model.js, line 495
Return Type:
DataSource
Example
var model =
    new falcor.Model({
        cache: {
            user: {
                name: "Steve",
                surname: "McGuire"
            }
        }
    }),
    proxyModel = new falcor.Model({ source: model.asDataSource() });

// Prints "Steve"
proxyModel.getValue("user.name").
    then(function(name) {
        console.log(name);
    });

batch(schedulerOrDelay) → {Model}

Returns a clone of the Model that enables batching. Within the configured time period, paths for get operations are collected and sent to the DataSource in a batch. Batching can be more efficient if the DataSource access the network, potentially reducing the number of HTTP requests to the server.

Parameters:
Name Type Description
schedulerOrDelay Scheduler or number

Either a Scheduler that determines when to send a batch to the DataSource, or the number in milliseconds to collect a batch before sending to the DataSource. If this parameter is omitted, then batch collection ends at the end of the next tick.

Source:
Model.js, line 438
Returns:

a Model which schedules a batch of get requests to the DataSource.

Return Type:
Model

boxValues() → {Model}

Returns a clone of the Model that boxes values returning the wrapper (Atom, Reference, or Error), rather than the value inside it. This allows any metadata attached to the wrapper to be inspected.

Source:
Model.js, line 515
Return Type:
Model

call(functionPath, args, refPaths, thisPaths)

Invokes a function in the JSON Graph.

Parameters:
Name Type Description
functionPath Path

the path to the function to invoke

args Array.<Object>

the arguments to pass to the function

refPaths Array.<PathSet>

the paths to retrieve from the JSON Graph References in the message returned from the function

thisPaths Array.<PathSet>

the paths to retrieve from function's this object after successful function execution

Source:
Model.js, line 214
Returns:

{ModelResponse. - a JSONEnvelope contains the values returned from the function

deref(derefPath, …relativePathsToPreload) → {Observable.<Model>}

Returns a new Model bound to a location within the JSONGraph. The bound location is never a Reference: any References encountered while resolving the bound Path are always replaced with the References target value. For subsequent operations on the Model, all paths will be evaluated relative to the bound path. Deref allows you to:

  • Expose only a fragment of the JSONGraph to components, rather than the entire graph
  • Hide the location of a JSONGraph fragment from components
  • Optimize for executing multiple operations and path looksup at/below the same location in the JSONGraph
Parameters:
Name & Attributes Type Description
derefPath Path

the path to the object that the new Model should refer to

relativePathsToPreload
repeatable
PathSet

paths (relative to the dereference path) to preload before Model is created

Source:
Model.js, line 292
Returns:
  • an Observable stream with a single value, the dereferenced Model, or an empty stream if nothing is found at the path
Return Type:
Observable.<Model>
Example
var model = new falcor.Model({
  cache: {
    users: [
      { $type: "ref", value: ["usersById", 32] }
    ],
    usersById: {
      32: {
	name: "Steve",
        surname: "McGuire"
      }
    }
  }
});
model.deref(["users", 0], "name").subscribe(function(userModel){
  console.log(userModel.getPath());
});

// prints ["usersById", 32] because userModel refers to target of reference at ["users", 0]

get(…path) → {ModelResponse.<JSONEnvelope>}

The get method retrieves several Paths or PathSets from a Model. The get method loads each value into a JSON object and returns in a ModelResponse.

Parameters:
Name & Attributes Type Description
path
repeatable
PathSet

the path(s) to retrieve

Source:
Model.js, line 137
Returns:
  • the requested data as JSON
Return Type:
ModelResponse.<JSONEnvelope>

getCache(…pathSetsoptional) → {JSONGraph}

Get the local JSONGraph cache. This method can be a useful to store the state of the cache.

Parameters:
Name & Attributes Type Description
pathSets
optional
repeatable
Array.<PathSet>

The path(s) to retrieve. If no paths are specified, the entire JSONGraph is returned.

Source:
Model.js, line 381
Returns:

all of the JSONGraph data in the Model cache.

Return Type:
JSONGraph
Example
// Storing the boxshot of the first 10 titles in the first 10 genreLists to local storage.
 localStorage.setItem('cache', JSON.stringify(model.getCache("genreLists[0...10][0...10].boxshot")));

getPath() → {Path}

Returns the Path to the object within the JSON Graph that this Model references.

Source:
Model.js, line 571
Return Type:
Path
Example
var model = new falcor.Model({
  cache: {
    users: [
      { $type: "ref", value: ["usersById", 32] }
    ],
    usersById: {
      32: {
	name: "Steve",
        surname: "McGuire"
      }
    }
  }
});
model.deref(["users", 0], "name").subscribe(function(userModel){
  console.log(userModel.getPath());
});

// prints ["usersById", 32] because userModel refers to target of reference at ["users", 0]

getVersion(pathnullable) → {Number}

Retrieves a number which is incremented every single time a value is changed underneath the Model or the object at an optionally-provided Path beneath the Model.

Parameters:
Name & Attributes Type Description
path
nullable
Path

a path at which to retrieve the version number

Source:
Model.js, line 399
Returns:

a version number which changes whenever a value is changed underneath the Model or provided Path

Return Type:
Number

invalidate(…path)

The invalidate method synchronously removes several Paths or PathSets from a Model cache.

Parameters:
Name & Attributes Type Description
path
repeatable
PathSet

the paths to remove from the Model's cache.

Source:
Model.js, line 242

preload(…path) → {ModelResponse.<Object>}

The preload method retrieves several Paths or PathSets from a Model and loads them into the Model cache.

Parameters:
Name & Attributes Type Description
path
repeatable
PathSet

the path(s) to retrieve

Source:
Model.js, line 169
Returns:
  • a ModelResponse that completes when the data has been loaded into the cache.
Return Type:
ModelResponse.<Object>

set() → {ModelResponse.<JSON>}

Sets the value at one or more places in the JSONGraph model. The set method accepts one or more PathValues, each of which is a combination of a location in the document and the value to place there. In addition to accepting PathValues, the set method also returns the values after the set operation is complete.

Source:
Model.js, line 153
Returns:
  • an Observable stream containing the values in the JSONGraph model after the set was attempted
Return Type:
ModelResponse.<JSON>

setCache(jsonGraph)

Set the local cache to a JSONGraph fragment. This method can be a useful way of mocking a remote document, or restoring the local cache from a previously stored state.

Parameters:
Name Type Description
jsonGraph JSONGraph

the JSONGraph fragment to use as the local cache

Source:
Model.js, line 349

treatErrorsAsValues() → {Model}

Returns a clone of the Model that treats errors as values. Errors will be reported in the same callback used to report data. Errors will appear as objects in responses, rather than being sent to the Observable~onErrorCallback callback of the ModelResponse.

Source:
Model.js, line 468
Return Type:
Model

unbatch() → {Model}

Returns a clone of the Model that disables batching. This is the default mode. Each get operation will be executed on the DataSource separately.

Source:
Model.js, line 451
Returns:

a Model that batches requests of the same type and sends them to the data source together

Return Type:
Model

unboxValues() → {Model}

Returns a clone of the Model that unboxes values, returning the value inside of the wrapper (Atom, Reference, or Error), rather than the wrapper itself. This is the default mode.

Source:
Model.js, line 525
Return Type:
Model

withoutDataSource() → {Model}

Returns a clone of the Model that only uses the local JSONGraph and never uses a DataSource to retrieve missing paths.

Source:
Model.js, line 535
Return Type:
Model

Type Definitions

comparator(existingValue, newValue) → {Boolean}

This function is invoked every time a value in the Model cache is about to be replaced with a new value. If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented.

Parameters:
Name Type Description
existingValue Object

the current value in the Model cache.

newValue Object

the value about to be set into the Model cache.

Source:
Model.js, line 61
Returns:

the Boolean value indicating whether the new value and the existing value are equal.

Return Type:
Boolean

errorSelector(jsonGraphError) → {Object}

This function is invoked on every JSONGraph Error retrieved from the DataSource. This function allows Error objects to be transformed before being stored in the Model's cache.

Parameters:
Name Type Description
jsonGraphError Object

the JSONGraph Error object to transform before it is stored in the Model's cache.

Source:
Model.js, line 54
Returns:

the JSONGraph Error object to store in the Model cache.

Return Type:
Object

onChange()

This callback is invoked when the Model's cache is changed.

Source:
Model.js, line 49