Value Object JS
The Value Object is a usefull, well known design pattern in a lot of languages. JavaScript is not one of them, until now. This plugin allows you to create your own 'Data types' as value object in order to better structure your application logic.
Installation
Bower
bower install --save value-object-js
<script src="/bower_components/value-object-js/dist/value-object.min.js"></script><script> var Email = ValueObject; // ...</script>
Besides the value-object.js file, this package also provides a set of predefined value objects like DateRang, Email, URL, YoutubeVideoURL and more. This library can be loaded on its own (value-object-library.min.js) or as part of the main file (value-ibject.with-library.min.js).
NPM
npm install --save value-object-js
var ValueObject = ; var Email = ValueObject; // ...
Usage
Define a value object
A value object only requires a name and a validation function testing the passed value.
var Email = ValueObject;
Using the defined value object is now as simple as instantiating any object using the new
keyword. Defined value objects can also be found in the library.
var customerEmail = 'example.domain.com'; // Throws InvalidArgumentException var customerEmail = 'example@domain.com'; // Works! var customerEmail = 'example@domain.com'; // Works!
The value object can now be handled like you would a String object.
console; // logs an object console; // logs 'Hi! Mail me at: example@domain.com'
Comparing value objects
Objects in javascript are equal on identity, not on value. Value objects, however, are equal on value and can be compared with strict equality. They even can be tested with instanceOf
.
var email1 = 'example@domain.com';var email2 = 'example@domain.com'; console; // logs trueconsole; // logs true
Adding methods
An email address is basicly a string, so it would be helpful if we could use the same methods. This can be done by specifying which data type (or other value object!) should be extended in the definition. You can also add your own methods.
var Email = ValueObject
Documentation
For full documentation see http://dev.tsoffereins.com/value-object-js/documentation/.
Support
You can reach me via Twitter: @tsoffereins
Please file issues here at GitHub.