Persistence responsibilities are divided between:
Batman.Modelencoders, which define serialization of model attributes
- Storage adapters, which perform storage operations with serialized data.
Persisted model attributes are defined with encoders. These are directives that tell batman.js to load certain keys from serialized data.
To encode and decode an attribute without transformation, pass one or more attribute names to
class MyApp.Product extends Batman.Model @encode 'title', 'description', 'price' class MyApp.Subscription extends MyApp.Product # Subscription inherits all encoders from MyApp.Product @encode 'period'
You can also define functions for encoding and decoding values by passing functions along with the attribute name(s):
class MyApp.Product extends Batman.Model @encode 'price', encode: (value, key, outgoingJSON, record) -> # adds values from `record` to `outgoingJSON` decode: (value, key, incomingJSON, outgoingAttributes, record) -> # takes values from `incomingJSON` and adds them to `outgoingAttributes`, # so they can be mixed into the record
Model.encode API docs for more information about custom encoders.
Also, model associations (
@hasMany, etc) define their own encoders.
Storage adapters (subclasses of
Batman.StorageAdapter) handle persistence operations:
You never call these functions directly, but
Batman.Model depends on them to save, load and destroy data.
Batman.js ships with a few storage adapters you can use right away:
Batman.LocalStoragefor storing data in local storage, if available.
Batman.SessionStoragefor storing data in session storage, if available.
Batman.RestStoragefor using RESTful HTTP (GET, POST, PUT, and DELETE) to store data in a backend app.
Batman.RestStoragewith some handy Rails-specific functionality like parsing out validation errors.
Use a storage adaper by passing to
@persist in a model definition:
class MyApp.Product extends Batman.Model @persist Batman.RestStorage
You can also extend any of the built-in storage adapters to:
- modify incoming and outgoing JSON
- include HTTP headers in requests
Batman.StorageAdapter API docs for more info.