Permalink
Fetching contributors…
Cannot retrieve contributors at this time
272 lines (229 sloc) 9.83 KB

Properties

< Clazz declaration | Main | Methods >

Sources: components/meta/Properties, components/meta/Property

There are two types of properties: clazz properties and instance properties. The only essential difference between these two types is that clazz properties are applied to clazz itself while instance properties are applied to it instances. Next meta directives are used for declaring these two types of properties:

  • clazz_properties - for clazz properties
  • properties - for instance properties

All internal options for these directives are absolutely the same.

Example:

Online working version of this example is available on plunker: http://plnkr.co/edit/oyF9jO

clazz('Person', {
    clazz_properties: {
        count: 1000,
        countries: {
            type: ['array', { element: ['string' , { pattern: /(\w+\s?)+/ }] }],
            default: []
        }
    },
    properties: {
        name: {
            type: 'string',
            constraints: {
                withoutNumbers: function(value) {
                    return (/[a-zA-Z]+/).test(value);
                }
            },
            methods: ['get', 'is' ] 
        },
        isIntelligent: ['boolean', true],
        birthday: ['datetime'],
        phone:    ['string', { pattern: /\d{1,2}-\d{3}-\d{5,7}/ }],
        sex: {
            converters: {
                fullForm: function(value) {
                    switch (value.toLowerCase()) {
                        case 'male':   value = 'M'; break;
                        case 'female': value = 'F'; break;
                    }
                    return value;
                },
                upperCase: function(value) {
                    return value.toUpperCase();
                }
            },
            constraints: {
                M_F: function(value) {
                    return -1 !== ['M','F'].indexOf(value)
                }
            },
            default: 'M',
        },
        skinColor: undefined,
        eyeColor: null,
        hairColor: 'black',
        address: function() {
            return 'some addres';
        }
    }
});

Type

Sources: components/meta/Property/Type.js

First of all you can specify type of property using type option. Property type can have its specific parameters. There are next property types (also their parameters are specified):

  • boolean - Converts property value into boolean value

  • number - Converts property value into number

    • min: Minimum for property value
    • max: Maximum for property value
  • string - Converts property value into string

    • pattern: Regular expression
    • variants: List of supported variants
  • datetime - Converts string and number into datetime or throw an error otherwise

  • array - Converts string into array of throw an error otherwise

    • element: Type for property element. It can be any type from this list. Parameters are also supported.
  • hash - Throw an error if value is not an simple object

    • element: Type for hash element. It can be any type from this list. Parameters are also supported.
    • keys: List of supported keys for hash.
  • object - Throw an error if value is not an object

    • instanceOf: value must be instance of this constructor function.
  • function - Throw an error if value is not a function

Default

Sources: components/meta/Property/Default.js

Using default option you can specify default value for property. If function is specified by way of default value, then return value of this function will be used as default value. Function will be executed in context of clazz or clazz instance depending on type of properties. If default value of property does not specified then property value equals undefined value.

Examples:

clazz('SomeClazzName', {
    properties: {
        name: {
            type: 'string',
            default: 'John'
        },
        age: ['number', 18],
        address: 'some city, some street',
        heirColor: function() {
            return Math.random > 0.5 ? 'white' : 'black';
        }
    }
});

Methods

Sources: components/meta/Property/Methods.js

You can genrate common methods for property manipulation. You must specify method types in methods option. Default value of methods option is [ 'get', 'set', 'has', 'is', 'remove', 'clear' ] (as you can see bellow this is all possible method types). It's using next logic for method name generation :

var methodName = methodType + propertyName[0].toUppersCase + propertyName.slice(1);

If property name starts with underscore characters then method name will be prefiexed with these underscrore characters.

Examples:

-----------------------------------------------------------------------------------------------
| property    | methods                                                                       |
|-------------|-------------------------------------------------------------------------------|
| name        | getName(), isName(), setName(), hasName(), clearName(), removeName()          |
| heirColor   | getHeirColor(), isHeirColor(), setHeirColor(), ...                            |
| _address    | _getAddress(), _isAddress(), _setAddress(), ...                               |
| __age       | __getAge(), __isAge(), __setAge(), __hasAge(), __clearAge(), __removeAge()    |
-----------------------------------------------------------------------------------------------

There are next method types:

  • get - property getter. Returns value of the property. Examples:
Person.getCountries();
person.getName();
person.getPhone();
person.getSex();
  • set - property setter. Returns this for fluent interface support. Examples:
Person
    .setCountries(['russia', 'usa', 'chine', 'france'])
person
    .setEyeColor('blue')
    .setHeirColor('white')
  • is - checker whether property is equals to specified value. If no value for matching is specified, then property value is converted to boolean and result is returned. Examples:
Person.isCount(1000);
person.isEyeColor('green');
person.isIntelligent();
  • has - check whether specified value exists. It means value must not be equal to 'undefined' or 'null'. Examples:
Person.hasCountries();
person.hasSkinColor();
person.hasEyeColor();
  • remove - remove property value. It set property value to 'undefined' or remove it in case of subproperties. (see bellow). Returns this for fluent interface support. Examples:
person.removeAddress();
person.removePhone();
  • clear - cleare property value. In contrast to 'remove' method it set property value of object and array types to {} and [] respectively. Returns this for fluent interface support. Examples:
Person.cleareCountries();
person.clearAddress(); // the same as person.removeAddress()

Constraints

Sources: components/meta/Property/Constraints.js

You can specify constraints for property. Each constraint has name and constraint logic - function. This function take setted value as first argument and must return true if constraint is satisfied and false otherwise. Constraint function is executed in context of clazz or clazz instance depending on properties type. If setted value does not satisfy the constraint error will be thrown.

Examples:

clazz('SomeClazz', {
    properties: {
        name: {
            constraints: {
                withoutNumbers: function(value) {
                    return (/[a-zA-Z]+/).test(value);
                },
                startsWithA: function(value) {
                    return 'A' === value[0];
                },
                endsWithY: function(value) {
                    return 'Y' === value[value.length - 1];
                },
            },
        }
    }
})

Converters

Sources: components/meta/Property/Converters.js

You can specify properties converters. Each converter has name and converter logic - function. This function takes setted value as first argument and returns converted (or not) value. Converter function is executed in context of clazz or clazz instance depending on properties type. Converters is applied to value before property constraints and type check.

Examples:

clazz('SomeClazz', {
    properties: {
        name: {
            converters: {
                toUpperCase: function(value) {
                    return value.toUpperCase();
                },
                addUnderscores: function(value) {
                    return '___' + value;
                },
                appendRandomNumber: function(value) {
                    return value + Math.floor(Math.random() * 1000);
                }
            }
        }
    }
});

< Clazz declaration | Main | Methods >

githalytics.com alpha