Category: VO

  • voFactory

    I use a lot value objects (VO) in Javascript storing JSON content and it is quite boring to create a new VO. So i did a factory to automate the process.

    Create a new VO:
    var TestVO = AMF.voFactory([
        ['name', {type: 'string'}],
        ['age', {type: 'int'}],
        ['height', {type: 'float'}],
        ['friends', {type: 'array', defaultValue: null, addName: 'friend'}],
        'x',
        ['y', {}]
    ]);

    Create a new instance on t:
    var t = new TestVO();

    Set values:
    t.setName('My Name');
    t.setAge(28);
    t.setHeight(1.74);
    t.setFriends(['Friend A', 'Friend B']);
    t.addFriend('Friend C');
    t.setX('value X');
    t.setY('value Y');

    Get values:
    t.getName() - My Name
    t.getAge() - 28
    t.getHeight() - 1.74
    t.getFriends() - Friend A,Friend B,Friend C
    t.getX() - value X
    t.getY() - value Y
    t.toString() -
        name: My Name,
        age: 28,
        height: 1.74,
        friends: [Friend A, Friend B, Friend C],
        x: value X,
        y: value Y
    t.serialize() - name=My%20Name&age=28&height=1.74& friends=Friend%20A%2CFriend%20B%2CFriend%20C& x=value%20X&y=value%20Y

    Using parse() method (JSON notation):
    var v = {'name': 'My New Name', 'age': 29, 'height': 1,76, 'friends': ['Friend D', 'Friend E'], 'x': 'value X2', 'y': 'value Y2'};
    t.parse(v);

    Get new values:
    t.getName() - My New Name
    t.getAge() - 29
    t.getHeight() - 1.76
    t.getFriends() - Friend D,Friend E
    t.getX() - value X2
    t.getY() - value Y2
    t.toString() -
        name: My Novo Name,
        age: 29,
        height: 1.76,
        friends: [Friend D, Friend E],
        x: value X2,
        y: value Y2
    t.serialize() - name=My%20Novo%20Name&age=29&height=1.76& friends=Friend%20D%2CFriend%20E& x=value%20X2&y=value%20Y2

    The methods parse(), toString() and serialize() are created as default, but you can reewrite anyone as you need.
    TestVO.prototype.parse = function() { ... };
    TestVO.prototype.toString = function() { ... };
    TestVO.prototype.serialize = function() { ... };

    Download it here (vofactory.zip 6kb)