Promised Models 2
Key features
- promise based
- typed attributes
- nested models and collections
- async calculations and validation
Install
$npm install --save promised-models2
Usage
var Model = FashionModel = attributes: name: ModelattributeTypesString model = name: 'Kate' ; model; // 'Kate'
Api reference (in progress)
Model sync methods
Model.inherit(properties, [classPorperties])
inherit Creates you own model class by extending Model
. You can define attributes, instance/class method and properties. Inheritance is built over inherit.
var CountedModels = Model;
Model.attributeTypes
attributeTypes Namespace for predefined types of attributes. Supported types:
Id
- for entity idString
Number
Boolean
List
— for storing arraysModel
— for nested modelsModelsList
— for nested collectionsCollection
- another implementation of collectionsObject
— serializable objects
You can extend default attribute types or create your own
var DateAttribute = ModelattributeTypesNumberFashionModel = Model;
Note: models.attributes
will be replaced in constructor with attribute instances.
var model = ;modelattributesbirthDate instanceof DateAttribute; //true
model.set(attributeName, value)
set Set current value of attribute.
var model = ;model;modelattributesname;model;
Note: setting null
is equivalent to call .unset()
model.get(attributeName)
get Get current value of attribute.
var model = name: 'Kate' birthDate: 1974 1 16model; //Katemodelattributesname; //Katemodel; //throws error as unknown attribute
model.toJSON()
toJSON Return shallow copy of model data.
Note: You can create internal attributes, which wouldn't be included to returned object.
var FashionModel = Modelmodel = name: 'Kate' surname: 'Moss' fullName: 'Kate Moss';model; // {fullName: 'Kate Moss'}model; // Kate
Note: Returned object supposed to be serializable via JSON.parse()
. Due to this reason NaN
and Infinity
are serialized in this way:
NaN -> null
Infinity -> 'Infinity'
model.getId()
getId Returns entity id. You can declare special id attribute, which will be interpreted as entity id. If id attribute is not declared, getId returns null
var FashionModel = Model; var model = myId: 1 name: 'Kate'; model // 1 FashionModel = Model; model = id: 1 name: 'Kate'; model // '1'
model.isChanged([branch])
isChanged Has model changed since init or last commit/save/fetch.
var FashionModel = Model model = name: 'Kate' weight: 55 ;model; //falsemodel;model; //true
model.commit([branch])
commit Cache current model state
var model = ;model;model;//truemodel;model;//false
model.revert([branch])
revert Revert model state to last cashed one
var model = name: 'Kate' weight: 55;model;model;model; //55model; //false
Note: You can create your own cache by passing branch param.
var RENDERED = 'RENDERED';model;
model.getLastCommitted([branch])
getLastCommitted Returns model last cached state.
model.previous([attr])
previous Returns attribute attr
previous value or model previous state if called without arguments.
model.on([attributes], events, cb, [ctx])
on Add event handler for one or multiple model events.
List of events:
change
– some of attributes have been changedchange:attributeName
–attributeName
have been changedcommit
- some of attributes have been committed to default branchbranch:commit
- some of attributes have been committed to branchbranch
commit:attributeName
-attributeName
have been committed to default branchbranch:commit:attributeName
-attributeName
have been committed to branchbranch
destruct
– model was destructedcalculate
– async calculations started
model ;
model.once([attributes], events, cb, [ctx])
on Same as model.on
but event handler will be called only once.
model.un([attributes], events, cb, [ctx])
un Unsubscribe event handler from events.
//subscribemodel; //unsubscribemodel;
model.destruct()
destruct Remove all events handlers from model and removes model from collections
model.isSet(attributeName)
isSet Returns true
if attribute was set via constructor or set
var model = ;model; //falsemodel;model; //true
model.unset(attributeName)
unset Set attribute to default value and model.isSet() === 'false'
var model = ;model;model;model; //falsemodel; //empty string (default value)
Model async methods
model.validate()
validate Validate model attributes.
var FashionModel = Model model = ; model;
Fulfilled attribute validation promise means that attribute is valid, otherwise it's not. Model.ValidationError#attributes
is array of attributes errors (Attribute.ValidationError
).
Note: For Model
and Collection
attributes validation
method is already defined. It validates nested entity and if it's not returns promise rejected with specific error contains nested errors.
If validate
returns promise rejected with String
this string will be used as message for Attribute.ValidationError
. If with something else (besides Boolean
) - rejected value will be available in Attribute.ValidationError#data
.
If attribute can be validated synchronously, you can define getValidationError
method. If it returns non-falsy value, validation promise will be rejected with returned value.
var FashionModel = Model model = ; model;
model.ready()
ready Fulfils when all calculations over model finished.
var FashionModel = Model model = ; model;model;
model.fetch()
fetch Fetch data associated with model from storage.
var FashionModel = Model model = id: id; model;
model.save()
save var FashionModel = Model model = ; model;model
model.remove()
remove Removes model from storage.
Model additional methods and properties
model.isNew()
model.isReady()
model.trigger(event)
model.calculate()
model.CHANGE_BRANCH
model.CALCULATIONS_BRANCH
These methods provided for advanced model extending. Consult source for details.
Model static methods and properties
Model.Storage
Storage Abstract class for model storage
var FashionModel = Model;
Model.storage
Class storage Storage class
var SuperModel = FashionModel;
Model.Attribute
Attribute Base class for model attribute
var CustomAttribute = Modelattribute
Model.attributes
Class attributes Model class attributes
var SuperModel = FashionModel;
Model.on([attributes], events, cb, [ctx])
Bind event on all models of class
FashionModel;
Model.un([attributes], events, cb, [ctx])
Unbind event on all models of class
List
Array like object returned for fields types List
and ModelsList
var Podium = Model.inherit({
attributes: {
models: Model.attributeTypes.ModelsList(FashionModel)
}
}),
podium = new Podium(data),
list = podium.get('models'), //instanceof List
model = list.get(0); //instanceof Model
Mutating methods
List inerits Array mutating methods: pop
, push
, reverse
, shift
, sort
, splice
, unshift
podium.get('models').push(new FashionModel());
list.get(index)
Get list item by index
podium.get('models').get(0);// instanceof Model
list.length()
Returns length of list
list.toArray()
Returns shallow copy of Array, wich stores List items
podium.get('models').forEach(function (model) {
model; // instanceof Model
});
Model.ValidationError
ValidationError Error class for validation fail report
Collection
Collection.inherit(properties, [classPorperties])
inherit Creates you own collection class by extending Collection. You should define modelType
property - constructor which will be used for new models.
var MyCollection = Collection;
collection.length
length Number of models in collection.
collection.at(index)
at Returns model by index.
collection.get(id)
get Returns model by id.
collection.where(conditions)
where Returns models that match the conditions.
var collection = name: 'John' age: 40 name: 'Bob' age: 40 name: 'Jane' age: 42; collection // -> [Model.<{name: 'John', age: 40}>, Model.<{name: 'Bob', age: 40}>]
collection.findWhere(conditions)
findWhere Same as where
but returns first match.
collection.pluck(attr)
pluck Picks one attribute from each model in collection and return array of these attributes.
var collection = name: 'John' age: 40 name: 'Bob' age: 40 name: 'Jane' age: 42; collection // -> ['John', 'Bob', 'Jane']
collection.add(models, [options])
add Adds new model(s) to collection. models
can be an object or instance of Model
or array of objects or models. Triggers add
event.
options
options.at
- position where model(s) should be inserted. By default model adds to end of colleciton
collection.remove(models)
remove Removes models from collection. models
can be an instance of Model
or array of models. Triggers remove
event.
Note: When model removes via model.remove()
it will be removed from collection
collection.set(models)
set Removes all models in collection and adds new models
Other methods
Collection implements some array methods: forEach
, some
, every
, filter
, map
, reduce
, find
.
Also collection proxies methods to models: isChanged
, commit
, revert
, toJSON
.
Model events
All model events such as change
, change:attribute
, calculate
, commit
, commit:attribute
also wil be triggered on collection
run tests
$ npm test