Skip to main content

Model

new Model(ooptional)

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
o
optional
Options

a set of options to customize behavior

Source:
Model.js, line 91

Members

getValue

Get data for a single Path.

Source:
Model.js, line 369
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 387
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

_setMaxSize(maxSize)

Reset cache maxSize. When the new maxSize is smaller than the old force a collect.

Parameters:
Name Type Description
maxSize Number

the new maximum cache size

Source:
Model.js, line 470

asDataSource() → {DataSource}

Adapts a Model to the DataSource interface.

Source:
Model.js, line 590
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 533
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 610
Return Type:
Model

call(functionPath, args, refPaths, extraPaths)

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

extraPaths Array.<PathSet>

additional paths to retrieve after successful function execution

Source:
Model.js, line 246
Returns:

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

deref(responseObject) → {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 Type Description
responseObject Object

an object previously retrieved from the Model

Source:
Model.js, line 339
Returns:
Return Type:
Model
Example
var Model = falcor.Model;
var model = new Model({
  cache: {
    users: [
      Model.ref(["usersById", 32])
    ],
    usersById: {
      32: {
        name: "Steve",
        surname: "McGuire"
      }
    }
  }
});

model.
    get(['users', 0, 'name']).
    subscribe(function(jsonEnv) {
        var userModel = model.deref(jsonEnv.json.users[0]);
        console.log(model.getPath());
        console.log(userModel.getPath());
   });
});

// prints the following:
// []
// ["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 179
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 453
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 675
Return Type:
Path
Example
var Model = falcor.Model;
var model = new Model({
  cache: {
    users: [
      Model.ref(["usersById", 32])
    ],
    usersById: {
      32: {
        name: "Steve",
        surname: "McGuire"
      }
    }
  }
});

model.
    get(['users', 0, 'name']).
    subscribe(function(jsonEnv) {
        var userModel = model.deref(jsonEnv.json.users[0]);
        console.log(model.getPath());
        console.log(userModel.getPath());
   });
});

// prints the following:
// []
// ["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 494
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 276

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

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 215
Returns:
  • a ModelResponse that completes when the data has been loaded into the cache.
Return Type:
ModelResponse.<JSONEnvelope>

set() → {ModelResponse.<JSONEnvelope>}

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 207
Returns:
  • an Observable stream containing the values in the JSONGraph model after the set was attempted
Return Type:
ModelResponse.<JSONEnvelope>

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 415

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 563
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 546
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 620
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 630
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 55
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 47
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 42