backbone-repository
Backbone extension that implements purposes of the Repository pattern, which means the enhancement of the model management and synchronization, so as to provide strong features to build online, offline and hybrid web applications.
The library mainly supports the following features:
- Model register: A Collection (C) keeps models instantiated.
- Sync modes: Sync modes (m) are sync functions to different data sources that are managed by a Repository (R).
- Sync state and operations: A Model (M) keeps changes not synchronized and run sync operations using a sync mode.
Versions
- backbone-repository - core library.
- backbone-respository-locally - core library + localStorage support through the Locally plugin.
Table of Contents
- Usage
- Reference API
- Building and Testing
- Release History
- License
Usage
Model register
The extension implements a model caching strategy. By this, a model register in the form of a collection will be responsible for keeping in-memory all instantiated models.
var User = BackboneModel; // A static method that returns the collection of usersvar userRegister = User;
Along with that, a factory method will manage such register and will instantiate or return a model ensuring that it is not instantiated twice according to its identifier attribute. Both model register and factory method will be accessed through a static method of the model.
// Creating instances through the factory methodvar user = User;var duplicate = User; // Ensures a model has been instantiated once.user === duplicate; // true // The user has been updated as well.user === "Nacho"; // true
Besides, collections will rely on the factory method to create the instances of the model class associated. So,
var Users = BackboneCollection;
Sync mode
A sync mode is responsible to provide logic to access to different data sources. There exists several predefined modes, but you are enable to configure your custom sync mode as well.
For using a mode, you must pass the mode as an option for every single sync operation, whether fetch, update, destroy, pull, push or check.
// E.g. fetching operation from server modeuser;
Server mode
The server mode uses the Backbone's sync function to perform a remote call against a REST API. It is the mode executed by default when using the model manager methods. Both the success and error callbacks are allowed in this mode.
Client mode
The client mode just perform local operations to the model. The success callback is only enabled in this mode.
LocalStorage mode (requires Locally extension)
The LocalStorage mode runs the model operations against LocalStorage. Both the success and error callbacks are allowed in this mode. For working, it requires Locally plugin and the "backbone-repository-locally" version of the library.
For using this mode, you must specify an storeName
whether in the model definition or by parameter when saving.
// Specify `storeName` in the model definition.var User = BackboneModel; var user = User; // Specify `storeName` when saving.user;
You may also specify an storagePrefix
for all your models when persisting in LocalStorage.
// Specify `storagePrefix`.BackbonestoragePrefix = "MyPrefix";
Finally, the LocalStorage key will read as follows: storagePrefix:storeName:[id|localId].
Custom mode
The extension features a way to configure your custom sync modes.
var { // sync function logic}; // Registers a new sync mode.BackboneRepository;
It is also possible to establish which mode will be selected by default.
// Defaults a sync mode.BackboneRepository;
Sync state
The model prototype has been expanded to work up the Repository features intented.
Fetch state
The fetch state means whether the model has been fetched against the sync mode or not.
user; user; // false
Dirty attributes state
The dirty attributes is a hash that keeps the model attributes that have changed since its last sync. For this, the set
method has been altered and configured to handle dirty changes.
// The 'set' method automatically stores dirtied attributes.// same happens to user.save({name: "Nacho"}, {mode: "client"});user; user; // true user; // outputs {name: "Nacho"}
The dirty handler may be turned off by passing dirty option to set
method.
// The 'set' method won't store dirtied attributes.user; user; // false
Dirty destroy state
The dirty destroy state means whether the model has been destroyed locally or not.
user; user; // true
Destroy state
The destroy state means whether the model has been destroyed against a sync mode or not.
user; user; // false
Version attribute
The version state is an attribute configured for each model. It is useful to stamp versions on the models when working with serveral data sources, for example a REST server and LocalStorage.
var User = BackboneModel;
When calling some operation that uses set
method, you are enabled to check if the version has been updated by passing an option. In case the model is outdated, it will force the fetched state to false
. An event named outdated
is also triggered when the version attribute is changed.
var user = User; user; // true, lets suppose that the model is fetched user; user; // false, the version has changed.
Sync operations
Along with predefined sync operations you can perform from a model such as fetch, save and destroy, the extension implements three useful methods: pull, push and check.
By default, all sync operations use the server mode, but it may use another one just by passing the mode as parameter.
Besides, all sync operations has been adapted to be used from Collection.
Pull method
The pull method performs a read request only if the model has not been fetched before.
var user = User; // Performs a sync call in its first fetching.user; // It won't request since it was fetched before.user;
Push method
The push method performs a request whether create, update or destroy methods according to the sync status.
// Create examplevar user = User; // A create request will be emitted.user; // Update exampleuser = User; // An update request will be emitted.user; // Destroy exampleuser; // A destroy request will be emitted.user;
Check method
The check method is devised to fetch only the model version attribute and check is up to date. This has the sense to be used with remote sync modes. The server mode is configured to accept the checkUrl
, which represent the checking endpoint.
var User = BackboneModel; var user = User; // Assuming that the user is already fetcheduser; // true user;
This method meant to be useful using through a Collection since you will verify the models all at once.
Reference API
Backbone.Repository
Backbone.Repository.modes()
modes Returns an array with the name of the available modes.
Backbone.Repository.getMode(name)
getMode Returns the sync function of the provided mode.
Available parameters:
- name {String} The mode name.
Backbone.Repository.setMode(name, [fn])
setMode Registers a new mode by provinding its name and sync function.
Available parameters:
- name {String|Object} The mode name or an object containing the name and sync function.
- fn {Function} The sync function
Backbone.Repository.getDefaultMode()
getDefaultMode Returns the default mode.
Backbone.Repository.setDefaultMode(name)
setDefaultMode Establish which mode will be used by default.
Available parameters:
- name {String} The mode name.
Backbone.Repository.removeMode(name)
removeMode Removes the sync mode registered.
Available parameters:
- name {String} The mode name.
Backbone.Repository.reset(name)
reset Cleans all the sync modes registered.
Backbone.Repository.storagePrefix
storagePrefix The prefix used in all storages. Requires Locally extension.
Backbone.Repository.compressStorage
compressStorage Wheter to use Locally compression by default or not. Requires Locally extension.
Backbone.Model
Backbone.Model.create(attrs, [options])
create Factory method that returns a model instance and ensures only one is gonna be created with same id.
Available parameters:
- attrs {Object} The attributes for the new instance.
- options {Object} The options for the new instance.
Backbone.Model.find(attrs)
find Returns a model by its id or cid from the local cache of the model.
Available parameters:
- attrs {Object} An id or cid for looking up.
Backbone.Model.register()
register Returns the collection that represents the local cache of the model.
Backbone.Model.reset()
reset Resets the local cache of the model.
model.isFetched([options])
isFetched Returns true
whether this model has been fetched through the sync mode or false
otherwise.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name for checking.
model.dirtied
dirtied Internal hash containing all attributes that have changed since the last sync for each sync mode.
model.dirtiedAttributes([options])
dirtiedAttributes Retrieve a copy of the attributes that have changed since the last sync.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
model.hasDirtied([options])
hasDirtied Returns true
in case the model changed since its last sync, false
otherwise.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
model.isDirtyDestroyed()
isDirtyDestroyed Returns true
if this model has been destroyed locally, false
otherwise.
model.clearDirtied()
clearDirtied Erases dirtied changes of the model, whether attribute change or model destroy.
model.set(attrs, [options])
set Alters set method to provide new options.
Available parameters:
- options.dirty {Boolean} [dirty=true] Whether to handle dirtied changes or not.
- options.version {Boolean} [version=true] Whether to handle version changes or not.
- options.localStorage {Boolean} [localStorage= true] Forces to save the model in LocalStorage. Requires Locally extension.
model.isDestroyed([options])
isDestroyed Returns true
if this model has been destroyed remotely, false
otherwise.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
model.pull([options])
pull Fetches the model using the sync mode selected if it has not been fetched before.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
model.push([options])
push Pushes the changes performed to the model using the sync mode selected. It may emitt create, update or destroy operations.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
model.checkUrl
checkUrl The checking endpoint in the server mode.
model.check([options])
check Fetches version attribute of the model and checks the uptodate status.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
- options.checkUrl {String} The checking endpoint in the server mode.
model.storeName
storeName The storage key for persisting the model. Requires Locally extension.
Backbone.Collection
collection.save(attrs, [options])
save Saves the whole collection using the sync mode. The server mode emitts one request per model.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
collection.destroy([options])
destroy Destroys the whole collection using the sync mode. The server mode emitts one request per model.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
collection.pull([options])
pull Pulls the whole collection using the sync mode. The server mode may emit urls that take the form of url+ subset of ids for fetching separated by comma.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
collection.push([options])
push Pushes the changes of the whole collection using the sync mode. The server mode emitts one request per model.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
collection.check([options])
check Checks the whole collection using the sync mode.
Available parameters:
- options.mode {String} [mode=defaultMode] The sync mode name.
- options.checkUrl {String} The checking endpoint in the server mode.
collection.storeName
storeName The storage key for persisting the collection. Requires Locally extension.
Building and Testing
First install locally all the required development dependencies.
npm install
Building
backbone-repository
grunt base
backbone-repository-locally
grunt baseLocally
Testing
grunt test
Release History
Read the CHANGELOG.md file distributed with the project.
License
Read the LICENSE file distributed with the project.