A simple model/collection extension for pacto.
Pacto.Model is available on NPM:
npm install pacto pacto.model --save
Pacto.Model only depends on Pacto which is dependency free, but it requires latest browser features. For Collection or Model you may need a polyfill for Proxy.
A model is an observed object. It detects changes to its properties and
dispatches a 'change'
event. All properties of a model instance are accessible
through the .props
property.
import {Model} from 'pacto.model';
const data = {foo: 'bar'};
const model = new Model(data);
model.on('change', () => console.log(model.props)); // logs: {foo: 'baz'}
model.props.foo = 'baz';
A model can be created using defaults for its properties. If one or more of these properties are not passed into the model, the model will use the predefined default values until the value will be set.
import {Model} from 'pacto.model';
class MyModel extends Model {
get defaults() {
return {foo: 'foo', baz: 'baz'};
}
}
const data = {foo: 'bar'};
const model = new MyModel(data);
console.log(model.props); // logs: {foo: 'bar', baz: 'baz'}
A collection is an observed array of Models. These models are
accessible through the .models
property. This property offers all
array functions.
When one of these functions changes the array, the collection instance
dispatches a 'change'
event.
All items which are passed into the collection will be transformed into a
Model. Which type of Model should be used is defined in the .Model
getter of a Collection instance.
import {Collection, Model} from 'pacto.model';
class MyModel extends Model {
get defaults() {
return {foo: 'foo', baz: 'baz'};
}
}
class MyCollection extends Collection {
get Model() {
return MyModel;
}
}
const collection = new MyCollection([{foo: 'bar'}]);
collection.on('change', () => console.log(collection.models)); // logs: [{foo: 'bar', baz: 'baz'}, {foo: 'foo', baz: 'bar'}]
collection.models.push({baz: 'bar'});