pacto.model

0.6.2 • Public • Published

Pacto.Model

CI Status Coverage Status on Codecov Known Vulnerabilities

A simple model/collection extension for pacto.

Installation

Pacto.Model is available on NPM:

npm install pacto pacto.model --save

Requirements

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.

Documentation

Model

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'}

Collection

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'});

License

LICENSE (MIT)

Package Sidebar

Install

npm i pacto.model

Weekly Downloads

9

Version

0.6.2

License

MIT

Unpacked Size

15 kB

Total Files

8

Last publish

Collaborators

  • nrmnrsh