0.0.9 • Published 6 years ago

track-model v0.0.9

Weekly downloads
2
License
ISC
Repository
github
Last release
6 years ago

TrackModel

A model of view.

Build Status

Installation

npm

npm install track-view-model

Usage

const TrackModel = require('track-view-model');

class Hoge extends TrackModel {
  static definer() {
    name('hoge'); // Define model name. **Required**

    accessor('hoge'); // Define `hoge.hoge` and `hoge.hoge=`
    reader('fuga');   // Define `hoge.fuga`
    writer('piyo');   // Define `hoge.piyo=`

    // Define accessor with onchange callback.
    accessor('foo', {onchanage: ((newly, older) => alert(`change ${older} to ${newly}`))});

    // Define validation of #hoge.
    // (require value, and value.length <= 100)
    validates('hoge', {presence: true, length: {max: 100}});
  }
}
const hoge = new Hoge({piyo: 'PIYO'});

hoge.hoge = 'hogehoge!';
hoge.hoge; // => "hogehoge!"

hoge.validate('hoge').then((result) => {
  console.log(result);
});

hoge.validateAll().then(/*...*/).catch(/*...*/);

hoge.toObject(); // => Object {hoge: 'abcdefg'}

Build-in validators

  • PresenceValidator
    • ex) validate('hoge', {presence: true})
      • ng) null undefined ''
  • LengthValidator
    • ex) validate('hoge', {length: {max: 10, min: 5}})
      • ng) 'abcd' 'abcdefghijk'
  • NumericalValidator
    • ex) validate('hoge', {numerical: {max: 10, min: 5}})
      • ng) 4 11 'abc'
  • FunctionValidator
    • ex) validate('hoge', {function: {validate: checkHoge}})
      • @see FunctionValidatorExample
  • FormatValidator
    • ex) validate('hoge', {format: {regex: /.+@.+/}})
      • ng) 'abcd'

FunctionValidatorExample

const Error = require('track-model/validators/error');
const checkHoge = function(value, resolve, reject) {
  if (value != 'hoge') {
    reject(new Error('is not Hoge.'));
  } else {
    resolve();
  }
};

validate('hoge', {function: {validate: checkHoge}})
0.0.9

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago