Neuro
An MVC framework that leverages MooTools.
Version: 0.2.8
Influences:
Credits/Thanks:
- Christoph Pojer for his work on Class.Binds for which I use and MooTools-Router which Neuro.Router is influenced from.
- Miller Medeiros for his work on crossroads.js which Neuro.Router is heavily influenced from.
- Dimitar Christoff for discussions on API and concepts.
- Elrood Sands for discussions on API for validation.
Dependencies:
Focus:
- leverage MooTools-Core
- provide base for applications
- provide a clean/clear API
Extensions:
- Neuro-Sync - Extends Neuro with a CRUD API
- Neuro-Company - Extends Neuro with an Observer API
Installation
Neuro is written as a CommonJS module and is available as an NPM package.
Node.js + NPM
Install Node.js + NPM and run the following command to install Neuro:
$ npm install Neuro
Afterwards, all you need to do to use Neuro is the following line in your scripts:
var Neuro = ;
Script Tags
There are pre-built scripts of Neuro at your disposal as well. All you need is the following code to load:
Choose between two files:
-
neuro.js - Packaged with WrapUp which exposes the
Neuro
object in the window global object -
neuro-min.js - Same as
neuro.js
but Uglified (obfuscated and compressed).
Build Your Own
Don't need everything in the Neuro object? Just want Neuro.Model? No problem! The pre-built files are created with WrapUp. So you can easily create your own as well!
Install Wrapup.
$ npm install -g wrapup
With Neuro installed (either locally or globally with the -g
flag), create a main.js
file. This file will be used to generate your own custom version of Neuro. We'll place it in a js/neuro
folder. For this example, we're just going to have Neuro.Model available. Create the main.js
file with the following:
exportsModel = Model;
Finally, we want to create the built file. Run this command while in the js/neuro
folder:
wrup -r Neuro ./main.js -o ./neuro.js
And voila, a custom neuro.js
file is created with Neuro
object containing only the Model
class.
Neuro Model
The Model is a Object-like MooTools Class object that provides a basic API to interact with data. You can use Model by itself or extend other Class objects with it. It implements each
, filter
, and other convenient methods from Object
.
Implements:
constructor (initialize)
Syntax:
var model = data options;
Arguments:
data
- (Object) An object containing key/value pairsoptions
- (Object, optional) The Model options- primaryKey - (String) Define to uniquely identify a model in a collection
- defaults - (Object) Contains the default key/value pair defaults for the Model.
- connector - (Object) See Mixin: Connector
- accessor - (Object) See Mixin: Butler
- validators - (Object) See Mixin: Snitch
Returns: Model instance.
Events:
change: function(model){}
- Triggered when a change to the model's data has occurredchange:key: function(model, key, value, oldValue){}
- Triggered when a specific model data property change has occurred. Thekey
refers to the specific property. Allchange:key
events will be triggered beforechange
is triggered.destroy: function(model){}
- Triggered when the model is destroyed.reset: function(model){}
- Triggered when the model is reset to its default values.error: function(model){}
- Triggered when the model data does not validate during the setting process.error:key: function(model, key, value){}
- Triggered when a specific model data property does not validate during the setting process.
Notes:
- Method names and properties prefixed with
_
is considered private and should not be used or directly interacted with.
Returns: Model instance.
set
The way to assign values to properties the model has. Do not use direct assignment else events will not be triggered or custom setters will not be used.
Syntax:
model; model;
Arguments:
- Two Arguments (property, value)
- property - (String) A key used to define a property the model has.
- value - (String | Array | Number | Object | Function | Class) A value of the corresponding property.
- One Argument (object)
- object (Object) An object containing sets of property/value pairs
Returns: Model instance.
Triggered Events:
change:key
change
Examples:
// set a property valuemodel'hasGlasses' true; // set the property 'name' as an object.model; set an object that contains all the property value pairsmodel;
isSetting
Use to check if data is currently being handled by the model to assign values to properties the model has.
Syntax:
model;
Returns: Boolean (true/false).
get
Retrieve a property value the model has.
Syntax:
model; model;
Arguments:
- More than One Consecutive Argument
- property1, property2... - (String) The properties used to retrieve corresponding values that the model has.
- One Argument
- property - (String) The property used to retrieve the corresponding value that the model has.
Returns:
- More than One Consecutive Argument
- (Object) Key/value pairs of data that the model has. Keys correspond to the arguments.
- One Argument
- (String) Value corresponding to the property that the model has.
Examples:
model; // returns value of 'name' property. model; // returns object containing name and age properties
getData
Retrieve all properties/values the model has. The returned object is a clone (dereferenced) of the data the model has.
Syntax:
model;
Returns: Object containing the data the model has.
getPrevious
Retrieve the previous property value he model had. Model only retains one record of previous data.
Syntax:
model; model;
Arguments:
- More than One Consecutive Argument
- property1, property2... - (String) The properties used to retrieve corresponding previous values that the model had.
- One Argument
- property - (String) The property used to retrieve the corresponding previous value that the model had.
Returns:
- More than One Consecutive Argument
- (Object) Key/value pairs of previous data that the model had. Keys correspond to the arguments.
- One Argument
- (String) Value corresponding to the previous property that the model had.
getPreviousData
Retrieve all previous properties/values the model had. THe returned object is a clone (dereferenced) of the previous data the model had.
Syntax:
model;
Returns: Object containing the previous data the model had.
unset
Unset data properties the model has. Data properties can not be erased so they will be set to undefined
.
Syntax:
model; model;
Arguments:
- property - (String | Array) The property to be unset that the model has. Multiple properties can be unset if they are encapsulated in an Array.
Returns: Model instance.
Triggered Events:
change:key
change
reset
Reset data properties to their default values the model had.
Syntax:
model; model; model;
Arguments:
- Zero Arguments
- all data properties in the model is reset to the defined options.defaults
- One Argument
- property - (String | Array, optional) The property to be reset that the model has. Multiple properties can be reset if they are encapsulated in an Array.
Returns: Model instance.
Triggered Events:
change:key
change
reset
destroy
Triggers the destroy
event. This should be overriden in a Class that extends from Model to do additional things. If overriden, remember to call this.parent();
to trigger the destroy
method, or execute signalDestroy
manually.
Syntax:
model;
Returns: Model instance.
Triggered Events:
destroy
toJSON
Returns a copy of data the model has. Can be used for persistence, serialization, or augmentation before passing over to another object. JSON.stringify
uses this to to create a JSON string, though the method itself does not return a String.
Syntax:
model;
Returns: Object containing the data the model has.
spy
A convenient method to attach event listeners to change:key
.
Syntax:
model
Arguments:
- Two Arguments
- property - (String) Name of the property to listen to.
- function - (Function) Function that is to be executed when event is triggered.
- One Argument
- object - (Object) An object encapsulating key/value pairs of properties/functions
Returns: Model instance.
unspy
A convenient method to remove event listeners to change:key
. If a function is not provided, all events attached to a specific change:key
will be removed.
Syntax:
model
Arguments:
- Two Arguments
- property - (String) Name of the property that is being listend to.
- function - (Function, optional) Function that is to be removed when event is triggered.
- One Argument
- object - (Object) An object encapsulating key/value pairs of properties/functions
Returns: Model instance.
setupValidators
see Mixin: Snitch
setValidator
see Mixin: Snitch
getValidator
see Mixin: Snitch
validate
Validate will test a property in Model
data against the validators defined in options.validators
. If a global validator ('*' or options.validators
is a function) is definined, the then the property is tested against the global validator, even if other validators are defined. A global validator can access other defined validators because the validator method is bound to this
, the Model
instance.
Synatx:
model;
Arguments:
- property - (String)
Name of property. Should reference an existing validator. If global validator is defined, the
property
is passed as the first argument to the global validator. - value - (String | Number | Object | Boolean | Array)
The
value
is what the validators will test against. If a global validator is defined, thevalue
is passed as the second argument to the global validator.
Returns: Boolean
Example:
// Test against a property in validators objectvar model = {} validators: // Test the 'name' property to make sure it is a string name: TypeisString ; model; // returns false model; // returns true // Test against a global validatorvar model2 = {} // Test property value to be a string or number { var type = ; return type == 'string' || type == 'number'; }; model2; // returns truemodel2; // returns falsemodel2; // returns true // Define a global validator to test against other defined validatorsvar model3 = {} validators: { // can only be name or age, and has to pass the validator return 'name' 'age' && thisvalue; } // Test the 'name' property to make sure it is a string name: TypeisString // Test the 'age' property to make sure it is a number age: TypeisNumber ; model3; // returns falsemodel3; // returns false model3; // returns falsemodel3; // returns true model3; // returns falsemodel3; // returns true
see Mixin: Snitch
proof
Method that proofs the model instance.
see Mixin: Snitch
Syntax:
model;
_validators
object must exist in the model instances _data
object and every function in _validators
must return true
in order for proof
to return true
, otherwise false
.
Returns: (Boolean) Every property in the proof
method, but makes use of it to "proof" the model instance.
Note: This overrides the original connect
see Mixin: Connector
disconnect
see Mixin: Connector
setupAccessors
see Mixin: Butler
isAccessing
see Mixin: Butler
setAccessor
see Mixin: Butler
getAccessor
see Mixin: Butler
unsetAccessor
see Mixin: Butler
addEvent
see Mixin: Events
addEvents
see Mixin: Events
removeEvent
see Mixin: Events
removeEvents
see Mixin: Events
fireEvent
see Mixin: Events
setOptions
see Mixin: Options
isSilent
see Mixin: Silent
silence
see Mixin: Silent
MooTools-Core Object Methods
The following methods have been implemented from MooTools-Core Object onto Neuro Model. They take the same arguments as their Object counterparts with the exception of having to pass the model as the object to be acted upon.
each
subset
map
filter
every
some
keys
values
getLength
keyOf
contains
toQueryString
model
Neuro Collection
The Collection is an Array-like MooTools Class object that provides a basic API to interact with multiple Models. You can use Collection by itself or extend other Class objects with it. It contains a reference to a Model Class to create a model instance when adding a data Object
. The reference Model Class can be optionally replaced by a different Class that extends from Model. It implements each
, filter
, and some other convenient methods from Array
.
Implements:
constructor (initialize)
Syntax:
var collection = data options;
Arguments:
data
- (Mixed, optional)- Model - A
Model
instance - Object - An object of key/value pairs that will be used to create a model instance
- Array - An array of Model instances or object key/value pairs
- Model - A
options
- (Object, optional)- primaryKey - (String) Define to uniquely identify a model in a collection
- Model - (Object, optional)
Contains the constructor and options for creating model instances during
add()
calls.- constructor (Class, optional, defaults to
Model
) TheModel
Class used to create model instances from when anObject
is passed toadd
. - options - (Object, defaults to undefined)
An
Object
containing options for creating new model instances. See Neuro Model
- constructor (Class, optional, defaults to
- connector - (Object) See Mixin: Connector
- validators - (Object) See Mixin: Snitch
Returns: Class instance.
Events:
change: function(collection){}
- Triggered when there is a change in the collection (add
,remove
,replace
).change:model: function(collection, model){}
- Triggered when there is a change in a model. Does not trigger thechange
event on the collection.add: function(collection, model){}
- Triggered when a model is added to the collection.remove: function(collection, model){}
- Triggered when a specific model is removed from the collection.empty: function(collection){}
- Triggered when the collection is emptied of all models.sort: function(collection){}
- Triggered whensort
orreverse
occurs.error: function(collection, model, at){}
- Triggered when a model is added to the collection that does not pass validation IF validators exist in the collection instance.
Notes:
- Method names and properties prefixed with
_
is considered private and should not be used or directly interacted with. - A default model is defined in the
Collection
Class as the_Model
property. It can be overriden byoptions.Model
or when a Class extends fromCollection
and defines a different_Model
property. - Define
options.primaryKey
to better identify model instances, such as checking if the collectionhasModel
.
Returns: Model instance.
hasModel
Checks if the collection instance contains a model by checking if the model exists in the _models
array or using options.primaryKey
to compare models.
Syntax:
currentCollection;
Arguments:
- model - (Object | Model) An
Object
orModel
instance that is used to compare with existing models in the collection.options.primaryKey
will be used to compare against the models if an initial use ofArray.contains
returnsfalse
.
Returns: Boolean.
add
Adding a model to the collection should always go through this method. It appends the model to the internal _model
array and triggers the add
event if the collection does not already contain the model. change
event is triggered afterwards.
If _validators
exist, then each model or object added must pass validation in order to be added to the collection instance. Otherwise a error
event will be triggered.
If an Object
is passed in, the Object
will be converted to a model instance before being appended to _model
. Adding a model will increase the collections length
property.
It is possible to insert a model instance into _model
at a specific index by passing a second argument to add
.
A remove
method is attached to the models destroy
event so that the model can be properly removed if the model destroy
event is triggered.
Syntax:
currentCollection;
Arguments:
- models - (Object | Model | Array)
- Object - An
Object
with key/value pairs of data properties. It will be converted to aModel
instance before adding to_model
. - Model - A
Model
instance. - Array - An
Array
that contain a mix ofObject
andModel
instances.
- Object - An
- at - (Number, optional) The index to insert the model in the
_model
array. If the collection is empty,at
is ignored and and the model is inserted as the first item in the array.
Returns: Class instance.
Triggered Events:
add
error
change
Examples:
currentCollection; currentCollection; currentCollection;
get
Get the model by index. Multiple indexes can be passed to get to retrieve multiple models.
Syntax:
currentCollection;
Arguments:
- index - (Number) The index number of the model to return.
_model
. If multiple indexes are passed to get
, an Array
of models is returned, where each model corresponds to the index.
Returns: A model instance corresponding to the index in Examples:
currentCollection; // returns the model instance that corresponds to the index argument currentCollection; // returns an array of model instances where each model corresponds to each index argument
remove
Remove a model or models from the collection. It will trigger the remove
event for each individual model removed. change
event is triggered afterwards.
The collection should remove the model only if it exists on the collection. Removing the model from the collection will also remove the remove
method from the models destroy
event.
Syntax:
currentCollection;
Arguments:
- model - (Model | Array) A model or array of models that will be removed from
_model
.
Returns: Class instance.
Triggered Events:
remove
change
Examples:
var model = id: 1 name: 'Garrick'; currentCollection; currentCollection; //or currentCollection; // remove an array of models.
replace
Replace an existing model in the collection with a new one if the old model exists and the new model does not exist in the collection _model
array. This will trigger add
and remove
events. change
event is triggered afterwards.
Syntax:
currentCollection;
Arguments:
- oldModel (Model) - The model that will be replaced in the collection.
- newModel (Object | Model) - The new model that will be replacing the old one.
Returns: Class instance.
Triggered Events:
add
remove
change
sort
Sort the collection. Works the same way Array.sort would work. Triggers sort
event.
Syntax:
currentCollection
Arguments:
- function - (Function, optional) The function acts as a comparator. Please see Array.sort for more information.
Returns: Class instance.
Triggered Events:
sort
Examples:
// Sorts models ordered by id, where id is a number.// This function sorts the order from smallest to largest number. currentCollection;
reverse
Reverses the order of the collection. Works the same way Array.reverse would work. Triggers sort
event.
Syntax:
currentCollection;
Returns: Class instance.
Triggered Events:
sort
empty
Empty the collection of all models. Triggers the empty
event and remove
event for each model removed.
Syntax:
currentCollection;
Returns: Class instance.
Triggered Events:
remove
for each model removedempty
toJSON
Returns a copy of collection _model
. Can be used for persistence, serialization, or augmentation before passing over to another object. JSON.stringify
uses this to to create a JSON string, though the method itself does not return a String.
Syntax:
currentCollection;
_model
.
Returns: Object containing the collection attachModelEvents
Attach handlers to the model destroy
and change
listeners. The model destroy
event will trigger the collection remove
method. The model change
event will trigger the collection change:model
event. This is automatically used during add
to help clean up if the model is destroyed and to notify listeners of the collection that a model changed.
Syntax:
currentCollection;
Arguments:
- model - (Model) A model instance to attach events to.
Examples:
var model = ; currentCollection; // Events attached to the model currentCollectionlength; // Return 1, meaning there is one model existing model; // currentCollection is notified that to remove the model since `destroy` event was triggered currentCollectionlength // Return 0, the model was removed when it was destroyed.
Returns: Class instance.
detachModelEvents
Detach handlers to the model destroy
and change
listeners. If the model destroy
event is triggered, the collection is notified and removes the model from the collection. The destroy
and change
events are removed from the model during execution of remove
method.
Syntax:
currentCollection;
Arguments:
- model - (Model) A model instance to attach events to.
Examples:
var model = ; currentCollection; // Events attached to the model currentCollectionlength; // Return 1, meaning there is one model existing model; // currentCollection is notified that to remove the model since `destroy` event was triggered currentCollectionlength // Return 0, the model was removed when it was destroyed.
Returns: Class instance.
setupValidators
see Mixin: Snitch
setValidator
see Mixin: Snitch
getValidator
see Mixin: Snitch
validate
Validate every property in a model that is passed into validate
.
see Mixin: Snitch
Syntax:
collection;
Arguments:
- models - (Object | Model | Array) An object, a model instance, or an array mix of both to be validated.
Returns: (Boolean) True if all properties in the models validate, false otherwise.
proofModel
Proof every property in the models that are passed into proofModel
. Every validator property needs to exist in the model and every validator function must return true
in order for proofModel
to return true
.
Syntax:
collection;
Arguments:
- model - (Object | Model | Array) An object, a model instance, or an array mix of both to be proofed.
Returns: (Boolean) True if all properties in the models proof, false otherwise.
proof
Method that proofs the models in the collection instance.
see Mixin: Snitch
Syntax:
collection;
Returns: (Boolean)
proof
method, but makes use of it to "proof" the collections models.
Note: This overrides the original addEvent
see Mixin: Events
addEvents
see Mixin: Events
removeEvent
see Mixin: Events
removeEvents
see Mixin: Events
fireEvent
see Mixin: Events
setOptions
see Mixin: Options
connect
see Mixin: Connector
disconnect
see Mixin: Connector
isSilent
see Mixin: Silent
silence
see Mixin: Silent
MooTools-Core Array Methods
The following methods have been implemented from MooTools-Core Array onto Neuro Collection. They take the same arguments as their Object counterparts with the exception of having to pass the collection as the object to be acted upon.
forEach
each
invoke
every
filter
clean
indexOf
map
some
associate
link
contains
getLast
getRandom
flatten
pick
collection
Neuro View
The View is a MooTools Class object. It acts as a layer between an element and everything else. One of the usual conventions of plugins that deals with elements has to attach/detach events to/from the element. The View provides a simple, yet basic, way of binding methods/functions to the element event listeners.
Another convention is that attaching event handlers to classes can be a manual process. View implements the Connector utility class to provide a powerful and automatic way to attach events between two classes.
The render
method is the main method that should be used to visualize the element with data. The method is basic, triggering the render
event on the View class. Other class objects should extend from the View class and override the render
method, but call this.parent
in order to trigger the render
event.
Implements:
constructor (initialize)
Starts out with executing setup
and then triggering ready
event.
Syntax:
var view = options;
Arguments:
options
- (Object, optional) The View options- element - (String | Element, defaults to
undefined
) The root/parent element of where the rendered elements should be placed. - events - (Object, defaults to
undefined
) AnObject
of key/value pairskey
- (String) The element event or event-delegate type.click
orclick:relay(selector)
value
- (String | Function | Array) The handler that is attached to the event. It can be aString
(amethod name in the view class instance),Function
, or anArray
of containing a mix ofString
orFunction
items.
- connector - (Object) See Mixin: Connector
- element - (String | Element, defaults to
Returns: View instance..
Events:
ready: function(view){}
- Triggered at the end of thesetup
method.render: function(view){}
- Triggered at the end of therender
method.inject: function(view){}
- Triggered at the end of theinject
method.dispose: function(view){}
- Triggered at the end of thedispose
method.destroy: function(view){}
- Triggered at the end of thedestroy
method.
Notes:
- Method names and properties prefixed with
_
is considered private and should not be used or directly interacted with.
setup
Called during initialize
to setOptions
, and setElement
.
Arguments:
- Same as
initialize
Returns: View instance.
toElement
A method to retrieve the element stored in the view instance. Any Class instance, with a toElement
method, passed to MooTools Element document.id
or $
method will return the value from the classes toElement
method. This is a hidden MooTools Core trick.
Syntax:
view; documentidview; ;
element
property stored in view instance.
Returns: setElement
Store the root element for the view instance. If an element exists, it will first execute View destroy
method to properly detach events and remove references to it. Then it will store a reference to the element and execute View attachEvents
.
Syntax:
view;
Arguments:
- element - (Element) Element to be set as root element in the view instance.
attachEvents
will refer tooptions.events
for the event and method/function to attach.
Returns: View instance.
attachEvents
Attach events to the root element
property in the view instance. It refers to options.events
to map element events to functions or methods in the view instance. Events can be detached using detachEvents
. element
or options.events
are required to exist.
Syntax:
view;
Returns: View instance.
detachEvents
Detach events from the root element
property in the view instance. It refers to options.events
to map element events to functions or methods in the view instance. Events can be attached using attachEvents
. element
or options.events
are required to exist.
Syntax:
view;
Returns: View instance.
create
It is a no-op method. Override create
in your Class that extends from View. It could be used to create the root element
, or other child elements that goes into the root `element.
Syntax:
view;
Returns: View instance.
render
Although render
is considered a no-op method, it still trggers the render
event. Override render
in your Class that extends from View. Remember to call 'this.parent()' at the end of your code to execute the original render
method that will trigger the render
event. Pass data
to the render
method, such as Neuro Model or Neuro Collection.
If you are passing any Class that implements Mixin: Connector, you should consider using the connect
method. It will help to automatically attach events between the View instance and the other Classes, in this case it is likely to be a Neuro Model or Neuro Collection instances.
Syntax:
view;
Arguments:
- data - (Mixed) It can be anything you will use as data to render the view. This also means you can pass in multiple Neuro Model instances, multiple Neuro Collection instances, other View instances. Use your imagination.
Returns: View instance.
Triggered Events:
render
inject
Inject or inserts the root element
relative to another element or View instance. document.id
/ $
will resolve the element from the other View instance.
Syntax:
view;
Arguments:
- reference - (String | Element | Class) The
element
will be placed relative to the reference element. AString
should be the id of the reference element, without the "#". AClass
instance should have atoElement
method in order to resolve the reference element. - where - (String, optional, defaults to "bottom") The place to inject/insert the
element
relative to the reference element. Can be:top
,bottom
,after
, orbefore
.
Returns: View instance.
Triggered Events:
inject
dispose
Removes the Element from the DOM but retains it in memory if the element
exists.
Syntax:
view;
Returns: View instance.
Triggered Events
dispose
destroy
Removes the Element and its children from the DOM and prepares them for garbage collection. Executes detatchEvents
and removes reference to element in element
property. Triggers destroy
event.
Syntax:
view;
Returns: View instance.
Neuro Route
The Route is a Class
object that extends from the Model
class object. It is heavily influenced by Crossroads.js by Miller Medeiros, as well as the documentation for it. A Route instance provides methods, amongst others, to test, parse, and interpolate data against a pattern.
Model
Extends:Implements:
constructor (initialize)
Syntax
var route = data options;
Arguments:
-
data
- (Object) An object containg key/value pairs. The properties in thedata
have default values.-
pattern
- (String | Regexp, optional, defaults toundefined
) String pattern or Regular Expression that should be used to match against requests.If pattern is a String it can contain named variables surrounded by
'{}'
that will be evaluated and passed to handlers as parameters. Each pattern segment is limited by the'/'
char, so named variables will match anything until it finds a'/'
char or the next string token located after the variable.The pattern
'{foo}/{bar}'
will match'lorem/ipsum-dolor'
but won't match'lorem/ipsum-dolor/sit'
. Trailing slashes at the end/begin of the request are ignored by default, so/{foo}/
matches same requests as{foo}
. - If you need to match segments that may contain "/" use a regular expression instead of a string pattern.A pattern can also have optional segments, which should be surrounded by
::
(e.g.'news/:foo:/:bar:'
will match'news'
,'news/123'
and'news/123/asd'
).If pattern is a RegExp, capturing groups will be passed as parameters to handlers on the same order as they were matched.
It also allows "rest" segments (ending with *) which can match multiple segments. Rest segments can be optional and/or required and don't need to be the last segment of the pattern. The pattern
'{foo}/:bar*:'
will match news'news/123'
,'news/123/bar'
,'news/123/lorem/ipsum'
.Support has been added to decoding query strings as well by starting the capturing groups with a
'?'
(eg:{?foo}
,:?bar:
). The matched value will be converted into an object. -
callback
- (Function, optional, defaults toundefined
) Function that should be executed when a request matches the Route pattern. It's just a convenient way to attach a handler to thematch
event. -
priority
- (Number, optional, defaults toundefined
) Route execution priority.Routes with higher priority will be tested during
Neuro.Router.parse
. It is important to note thatNeuro.Router
will stop pattern tests as soon as it finds a Route that matches the request. Setting the priority is a way to invert “natural” test order. Routes are tested by order of creation if priority is omitted. -
normalizer
- (Function, optional, defaults toundefined
) A function that should be used to normalize parameters. Works similarly toRoute
rules.normalize_
.normalizer
will be used ifrules.normalizer_
does not exist. If both normalize functions do not exist, then, obviously, normalizing parameters will not occur. -
greedy
- (Boolean, optional, defaults tofalse
) Used to determine whetherNeuro.Router
should try to match thisRoute
instance after having matched anotherRoute
instance.Neuro.Router
will trigger all "greedy"Routes
that match the request duringparse
in theNeuro.Router
instance. -
rules
- (Model, Object, optional, defaults to{}
) Object used to configure parameters/segments validation rules.Validation rules can be an Array, a RegExp or a Function:
- If rule is an Array, crossroads will try to match a request segment against items of the Array, if item is found parameter is valid.
- If rule is a RegExp, crossroads will try to match a request segment against it.
- If rule is a Function, crossroads will base validation on value returned by Function (should return a Boolean).
Rules keys should match route pattern segment names or should be a numeric value, starting at index 0, that match each RegExp capturing group or path segment.
The rules object can also contain 2 special properties
request_
andnormalize_
:-
normalizer_
- (Function(request, values), optional) Used to modify/normalize values before triggering thematch
event byNeuro.Router
. It should return an Array with parameters that should be passed to listeners.Can be used to create route aliases and also to convert data format.
Works exactly like
options.Model.options.defaults.normalizer
inNeuro.Router
. It will overwriteoptions.Model.options.defaults.normalizer
inNeuro.Router
if present. -
request_
- (Array | RegExp | Function) Rule used to validate whole request.request_
is a special rule used to validate whole request Note that request will be typecasted if value is a boolean or number andoptions.Model.options.defaults.typecast
= true (default = false) inNeuro.Router
.
-
typecast
- (Boolean, optional, defaults tofalse
) Type cast route paths with this property.true
typecasts values in the route path, whilefalse
typecasts them as strings. -
patternLexer
- (Object, optional, defaults toRoute.PatternLexer
) The pattern lexer isundefined
. Mixin: Butler, the custom accessor, allows defining a custom pattern lexer for each individual route, but defaults to using the globalRoute.PatternLexer
.
-
-
options
- (Object, optional) See Model.
Returns: Route instance.
Neuro.Model
):
Events (Includes events inherited from match: function(route[, param1, param2, param3...]){}
- Triggered whenNeuro.Router
has found a match.Neuro.Router
will pass each captured parameter to the handler function.pass: function(route[, request]){}
- Triggered whenNeuro.Router
has changed from one route to the next. Therequest
parameter passed to the event refers to the current request that is being changed to.
Examples:
// Create a new route with a patternvar route = pattern: 'person/{name}'; // Test a string against the routeroute; // returns trueroute; // returns false
match
Test if the Route
instance matches against a string.
Syntax:
route;
Arguments:
string
- (String) The string which will be tested against heRoute
instances rules and pattern.
Returns: Boolean (true/false).
Examples:
// Create a new route with a patternvar route = pattern: 'person/{name}'; // Test a string against the routeroute; // returns trueroute; // returns false
parse
Parse a string for matches against the Route
instances pattern.
Syntax:
route;
Arguments:
string
- (String) The string which will be parsed for matches against theRoute
instances pattern.
Returns:
- Found matches
- An array of matched items
- No matches
null
Examples:
// Create a new route with a patternvar route = pattern: 'person/{name}'; route; // returns ['bruce']route; // returns null
interpolate
Generates a string that matches the route by replacing captured groups in the Route
instances pattern with the replacements
values provided.
Syntax:
route;
Arguments:
replacements
- (Object) Contains key/value pairs to match and replace captured groups in the pattern.
Returns: String.
Examples:
// Create a new route with a patternvar route = pattern: 'person/{name}'; route; // returns 'person/awesome'
Neuro Router
The Router is a Class
object that extends from the Collection
class object. It is heavily influenced by Crossroads.js by Miller Medeiros, as well as the documentation for it. It parses string input to decide what action should be taken by matching the string against mutiple patterns (Route
instances).
Collection
Extends:Implements:
constructor (initialize)
Syntax:
var router = routes options;
Arguments:
routes
- (Mixed, optional)- Route - A
Route
instance. - Object - An object of key/value pairs that will be used to create a
Route
instance. - Array - An array of
Route
instances or object key/value pairs.
- Route - A
options
- (Object, optional) See Collection for the other options inherited fromCollection
-
Model
- (Object, optional) Contains the constructor and options for creating route instances duringadd()
calls.constructor
- (Route, optional) Override this at your own risk. If it is overriden, be sure that the value is aClass
and that it at least extends fromRoute
.options
- (Object, optional) Sets theoptions
forRoute
instances during theadd
method call. Check Neuro Modeldefaults
- (Object, optional) Sets the default properties forRoute
instances during theadd
method call. Check Neuro Route for the properties
-
greedy
- (Boolean, optional, defaults tofalse
) Set tofalse
will stop on the first match with the supplied request.Set to
true
will try to match every singleRoute
instance with the supplied request. -
greedyEnabled
- (Boolean, optional, defaults totrue
) Iffalse
it won't try to match multiple routes (faster).
-
Returns: Route instance.
Events:
match: function(router, request, data){}
- Triggered whenRouter
instance finds a match duringparse()
.router
- (Router) TheRouter
instance.request
- (String) The string being parsed.data
- (Object) Contains data pertaining to matchingRoute
instance.route
- (Route) The matchingRoute
instanceparams
- (Array) An array containing parameters captured by theRoute
instances patternisFirst
- (Boolean)true
for the first timematch
event is triggered during theparse()
method call. Will befalse
unless theRoute
instance isgreedy
and it is being matched after anotherRoute
instance already matched therequest
.
default: function(router, request){}
- Triggered whenRouter
instance does not find a match duringparse()
.router
- (Router) TheRouter
instance.request
- (String) The string being parsed.
Examples:
/*Create a router instance. Note the typecast property in Model.options.defaults object.This will typecast the captured group so that rules can be simple functions like Type.isString.Otherwise all values passed to the rules will be strings. */var router = pattern: 'news/{id}' rules: id: TypeisNumber { console; } { console; } Model: options: defaults: typecast: true ; /*typecast property needs to be manually set here because Model.options object is onlyused when a Route instance is created by the Router instance during the add method call. */router; // triggers default eventrouter; // triggers default event because 'a' is typecast as a stringrouter; // triggers match on the 'news/{id}' pattern because '123' is typecast to a number and passes the rule for 'id'router; // triggers default event because '123' is typecast as a number and does not pass the 'type' rule for 'news/{type}/{id}' patternrouter; // triggers match on the 'news/{type}/{id}' pattern because 'abc' is typecast to a string and passes the rule for 'type'// and '456' is typecast as a number and passes the rule for 'id'router;
parse
Parse a string input and trigger the first matching Route
instances match
event. Routing priority is defined by order of insertion or by the priority
property of each Route
instance.
Syntax:
router;
Arguments:
request
- (String) String that should be evaluated and matched againstRoute
instances to define whichRoute
match
event handlers should be executed and which parameters should be passed to thematch
event handlers.defaultArgs
- (Array, optional) Array containing values passed tomatch
/default
signals as first arguments. Useful for node.js in case you need to access the request and response objects.
Returns: Router instance.
Events:
pass
Route
instancematch
match
default
Notes:
The parse algorithm is very straightforward, since the string patterns were already converted into regular expressions during add
method call the router just need to loop through all the routes (following the priority order) and check which one matches the current input. If it does find a route that matches the request
it will check if the route contains the special property rules and then it will validate each segment (capturing group). If after all that the route is considered "matched", then the previous Route
's pass
event is triggered and the Route
match
event is triggered together with the Router
's match
event. Otherwise the Router
's default
event is triggered.
Calling parse
multiple times in a row passing the same request will trigger the match
/Route
instance match
/default
signals only once.
Examples:
/*typecast property needs to be manually set here because Model.options object is onlyused when a Route instance is created by the Router instance during the add method call. */var route1 = pattern: 'news/{id}' rules: id: TypeisNumber // the 'match' event handler on the route { console; } typecast: true; route1; var route2 = pattern: 'news/{type}/{id}' rules: type: TypeisString id: TypeisNumber // the 'match' event handler on the route { console; } typecast: true; route2; /*Create a router instance. Note the typecast property in Model.options.defaults object.This will typecast the captured group so that rules can be simple functions like Type.isString.Otherwise all values passed to the rules will be strings. */var router = route1 router2; /*router 'default' event is triggered. */router; /*route1 'match' event is triggered.router 'match' event is triggered.no 'pass' event is triggered because there was no matching route in the previous parse method call. */router; /*route1 'pass' event is triggered.route2 'match' event is triggered.router 'match' event is triggered. */router;
resetState
Resets the Router
instances internal state. Will clear reference to previously matched Route
instances (so they won't trigger pass
events when matching a new route) and reset last request.
This feature should NOT be needed by most users.
Syntax:
router;
Returns: Router instance.
Examples:
var route1 = pattern: 'news/{id}' rules: id: TypeisNumber // the 'match' event handler on the route { console; } typecast: true; route1; var route2 = pattern: 'news/{type}/{id}' rules: type: TypeisString id: TypeisNumber // the 'match' event handler on the route { console; } typecast: true; route2; /*Create a router instance. Note the typecast property in Model.options.defaults object.This will typecast the captured group so that rules can be simple functions like Type.isString.Otherwise all values passed to the rules will be strings. */var router = route1 router2; /*route1 'match' event is triggered.no 'pass' event is triggered because there was no matching route to begin with. */router; /*route1 'pass' event is triggered.route2 'match' event is triggered. */router; // Remove references to previous request and routerouter; /*route1 'match' event is triggered.no 'pass' event is triggered references to previous request and route have been removed. */router;
Mixin: Events
From MooTools Documentation:
A Utility Class. Its methods can be implemented with Class:implement
into any Class. Events
in a Class that implements Events
must be either added as an option or with addEvent
, not directly through .options.onEventName
.
Syntax:
For new classes:
var MyClass = Implements: Events ;
For existing classes:
MyClass;
Implementing:
- This class can be implemented into other classes to add its functionality to them.
Events
has been designed to work well with theOptions
class. When the option property begins with 'on' and is followed by a capital letter it will be added as an event (e.g.onComplete
will add ascomplete
event).
Example:
var Widget = Implements: Events { // ... } { this; }; var myWidget = ;myWidget;
Notes:
- Events starting with 'on' are still supported in all methods and are converted to their representation without 'on' (e.g. 'onComplete' becomes 'complete').
addEvent
Adds an event to the Class instance's event stack.
Syntax:
myClass;
Arguments:
- type - (String) The type of event (e.g.
complete
). - fn - (Function) The function to execute.
- internal - (Boolean, optional) Sets the function property: internal to true. Internal property is used to prevent removal.
Returns: This Class instance.
Example:
var myFx = 'element' 'opacity';myFx;
addEvents
The same as addEvent
, but accepts an object to add multiple events at once.
Syntax:
myClass;
Arguments:
- events - (Object) An object with key/value representing: key the event name (e.g.
start
), and value the function that is called when the Event occurs.
Returns: This Class instance.
Example:
var myFx = 'element' 'opacity';myFx;
fireEvent
Fires all events of the specified type in the Class instance.
Syntax:
myClass;
Arguments:
- type - (String) The type of event (e.g.
complete
). - args - (String | Array, optional) The argument(s) to pass to the function. To pass more than one argument, the arguments must be in an array.
- delay - (Number, optional) Delay in milliseconds to wait before executing the event (defaults to 0).
Returns: This Class instance.
Example:
var Widget = Implements: Events { //... this; };
removeEvent
Removes an event from the stack of events of the Class instance.
Syntax:
myClass;
Arguments:
- type - (String) The type of event (e.g.
complete
). - fn - (Function) The function to remove.
Returns: This Class instance.
Notes:
- If the function has the property internal and is set to true, then the event will not be removed.
removeEvents
Removes all events of the given type from the stack of events of a Class instance. If no type is specified, removes all events of all types.
Syntax:
myClass;
Arguments:
- events - (optional) If not passed removes all events of all types.
- (String) The event name (e.g. 'success'). Removes all events of that type.
- (Object) An object of type function pairs. Like the one passed to
addEvents
.
Returns: This Class instance.
Example:
var myFx = 'myElement' 'opacity';myFx;
Notes:
- removeEvents will not remove internal events. See
Events:removeEvent
.
Mixin: Options
From MooTools Documentation:
A Utility Class. Its methods can be implemented with Class:implement
into any Class. Used to automate the setting of a Class instance's options. Will also add Class Events
when the option property begins with 'on' and is followed by a capital letter (e.g. onComplete
adds a complete
event). You will need to call this.setOptions()
for this to have an effect, however.
Syntax:
For new classes:
var MyClass = Implements: Options;
For existing classes:
MyClass;
setOptions
Merges the default options of the Class with the options passed in. Every value passed in to this method will be deep copied. Therefore other class instances or objects that are not intended for copying must be passed to a class in other ways.
Syntax:
myClass;
Arguments:
- options - (Object, optional) The user defined options to merge with the defaults.
Returns: This Class instance.
Example:
var Widget = Implements: Options options: color: '#fff' size: width: 100 height: 100 { this; }; var myWidget = color: '#f00' size: width: 200 ; //myWidget.options is now: {color: #f00, size: {width: 200, height: 100}} // Deep copy examplevar mySize = width: 50 height: 50; var myWidget = size: mySize; mySize == myWidgetoptionssize // false! mySize was copied in the setOptions call.
Notes:
- Relies on the default options of a Class defined in its options property.
Options in combination with Events
If a Class has Events
as well as Options
implemented, every option beginning with 'on' and followed by a capital letter (e.g. onComplete
) becomes a Class instance event, assuming the value of the option is a function.
Example:
var Widget = Implements: Options Events options: color: '#fff' size: width: 100 height: 100 { this; } { // Do some cool stuff this; } ; var myWidget = color: '#f00' size: width: 200 { ; }; myWidget; // fires the event and alerts 'Lets show it!'
Mixin: Connector
A Utility Class. It allows automatic attachment/detachment of event listeners between two classes.
options.connector
A key/value object to map events to functions or method names on the target class that will be connected with. The value can also be an object that contains more key/value pairs. This allows to attach sub-events, such as change:key
. Note: An asterisk (*) as the sub-event refers to the parent event only.
Note: Using a nested object in options.connector
as the map is possible via a name
param when using connect
or disconnect
. Doing so means that connecting/disconnecting the class will ALWAYS have to designate the name
param. If you don't, then issues will occur because then Connector will treat nested objects key/value pairs as sub-events.
PowerTools! Class.Binds
Implements:Syntax: key/value pairs
// Shallow object event: method // Nested object name: object
Arguments
- Shallow object
- event - (String) The name of the event to be attached. It becomes the parent event if the events corresponding value is an object.
- method - (String, Function, Array, Object)
- String - Refers to a method on the target class. The method will be bound to the target class and attached as the event handler.
- Function - The function will be bound to the current class and attached as the event handler
- Array - Can contain a mix of
String
(name of method to retrieve said method from target class) orFunction
to be attached as the event handler - Object - Contains key/value pairs where
key
will refer to the sub-event and value refers toString
,Function
, orArray
to attach as event handlers. The sub-event will be prepended by theevent
with a:
.
- Nested Object
- name - (String) Name of the object that would be used as the map during connect/disconnect
- object - (Object) The shallow object that is used as the map during connect/disconnect
Examples
The following will show what key/value pairs will look like and what they look like when attached manually instead of with connector.
value
is a string
change: 'doneMethodName'
currentClass;
value
is a function
{/*... code here ...*/}
currentClass;
value
is an array
change: 'doneMethodName' {/*... code here ...*/}
currentClass; currentClass;
value
is an object with subevents and a mix of string, function, or array.
change: '*': 'doneMethodName' {/*... code here ...*/} 'age': 'otherDoneMethodName' {/*... other code here ...*/}
currentClass; currentClass; currentClass; currentClass;
connect
Connects two classes by using options.connector
as the map to either attach event listeners to functions on options.connector
or methods on the target class where the method names are retrieved from options.connector
. Default behavior is to connect one class. Connect both ways by passing a second argument as true
.
A name of a specific object in options.connector
can be passed as the second argument and that object will be used as the map. If connecting both ways, the same name
will be used. Connect both ways by passing a third argument as true
.
Syntax
currentClass; currentClass;
Arguments
- class - (Class) The class containing the methods that will be attached as event handlers to event listeners on the current class.
- name - (String, optional) Name of a specific object in
options.connector
to be used as the map. - oneWay - (Boolean, optional,
false
by default) Set to true will only connectthis
class with the target class and will not have the target class connect withthis
class.
Returns: Class instance.
Examples:
// Using options.connector object by defaultcurrentClassoptionsconnector = 'add': 'doAddStuff'; targetClassoptionsconnector = 'remove': 'doRemoveStuff'; /** * Bind one way. * * Basically does currentClass.addEvent('add', targetClass.doAddStuf.bind(targetClass)); */currentClass; /** * Bind both ways. * Basically does: * * currentClass.addEvent('add', targetClass.doAddStuf.bind(targetClass)) * and * * targetClass.addEvent('remove', currentClass.doRemoveStuff.bind(currentClass)); */currentclass; // Using specific object that is nested in options.connectorcurrentClassoptionsconnector = 'classSpecific': 'add': 'doAddStuff' ; targetClassoptionsconnector = 'classSpecific': 'remove': 'doRemoveStuff' ; /** * Bind one way. * * Basically does currentClass.addEvent('add', targetClass.doAddStuf.bind(targetClass)); */currentClass; /** * Bind both ways. * Basically does: * * currentClass.addEvent('add', targetClass.doAddStuf.bind(targetClass)) * and * * targetClass.addEvent('remove', currentClass.doRemoveStuff.bind(currentClass)); */currentclass;
disconnect
Does the opposite of what connect
does. Takes the same arguments.
bound
A method provided by PowerTools! Class.Binds.
Provides an alternative way to bind class methods. Stores references to bound methods internally without any manual setup and does not modify the original methods.
The retrieved function is bound to the class instance.
Syntax:
currentClass;
Arguments:
- methodName - (String) Name of the method that has been bound to the class instance and stored.
PowerTools! Class.Binds)
Examples: (Slightly modified from var currentClass = Implements: Connector { thiselement = documentidelement; this; } { // Add the click method as event listener thiselement; } { // Retrieves the same reference to the click method and removes the listener thiselement; } { event; // doSomething this; };
Mixin: Butler
A Utility Class. It provides a way to define custom setters/getters on a Class.
options.accessors
A key/value object where the key is the name of the setter and value is an object containing overriding set/get methods.
Syntax: key/value pairs
name:
Arguments
- name - (String) Name of the set/get method that will get overriden
- object - (Object) Contains set, get method overrides.
- set - (Function) The overriding set function. The function will be bound to the current class.
- get - (Function) The overriding get function. The function will be bound to the current class.
setupAccessors
Existing accessors in _accessors
are merged with options.accessors
before being sent to setAccessor
. This should be called in the initailize
or setup
method.
Syntax:
currentClass;
Returns: Class instance.
isAccessing
Check whether an accessor is being used by checking if _accessorName
has been defined. This will allow a class to bypass recursive calls to the same custom setter/getter.
Syntax:
currentClass;
Returns: Boolean
setAccessor
A method to decorate custom setters/getters that will allow the use of isAccessing
to prevent recursive calls to the same custom setter/getter. The decorated custom setters/getters is an object of name/function pairs that is stored in _accessors
by name.
Syntax:
currentClass; currentClass;
Arguments:
- Two Arguments
- name - (String) Name of the accessor setter/getter object.
- obj - (Object) Key/value pairs where the
key
isset
orget
andvalue
is the function. Any key/value pair is optional. Aset
can exists without aget
, and aget
can exist without aset
.
Returns: Class instance.
_orig
attribute.
Note: The original undecorated function is stored on the decorated function in the Example:
var klass = Implements: CustomAccessor options: accessors: fullName: {} ; var currentClass = ; // manually executed because klass doesn't have an initialize or setup method to execute setupAccessors.currentClass; var fullNameAccessor = currentClass; fullNameAccessorset; // returns the decorated set function. fullNameAccessorset_orig // is the undecorated original set function.
getAccessor
A method to retrieve stored accessors by name or by name and type.
Syntax:
currentClass;
Arguments:
- name - (String) The name of the accessor object to return.
- type - (String, optional) The name of the method that exists in the accessor object.
Returns:
- Object - The object of decoerated key/value pairs containing the accessors that was stored with the name.
- Function - The decorated function that is associated with the
type
in the accessor object. The accessor object is retrieved with thename
.
Examples:
Return an accessor object
currentClass; var fullNameAccessors = currentClass;/*fullNameAccessors returns and object where the set function is the decorated function{ set: function(){}} */
Return the decorated function in the accessor object
// Returns the decorated function that is stored with the set key, in the fullName accessor object.var fullNameSetAccessor = currentClass;
unsetAccessor
Remove an accessor object or decorated function from the accessor object.
Syntax:
currentClass;
Arguments:
- name - (String) The name of the accessor object to remove.
- type - (String, optional) The
key
of the function that should be removed from the accessor object.
Returns: Class instance.
Example
Remove an accessor object
currentClass;
Remove a function from the accessor object
currentClass;
Mixin: Silent
A Utility Class. It provides a solution to disable before a function executes, and re-enabling afterwards.
isSilent
Checks if the Class is currently silent.
Syntax:
currentClass;
Returns: Boolean
silence
Any method that can trigger an event can be temporarily disabled by passing the function through silence. Once the function has been triggered, events will be re-enabled.
Syntax:
currentClass
Arguments:
- function - (Function) The function that will be executed once events have been prevented. The function is bound to the model instance before execution.
Returns: Class instance.
Mixin: Snitch
A Utility Class. Use this class to set/get validator functions. A validate
method offers a way to easily retrieve a validator to test a value. A proof
method is a simple object spec test that tests an object for existence of keys and runs validation tests on the values of those keys.
options.validators
A key/value object where the key is the property name and value is a function. The function will be passed an argument to test against and should return a boolean.
Syntax: key/value pairs
Arguments
- name - (String) Name of the validator function
- function - (Function) The function will be passed an argument to test against and should return a
Boolean
setupValidators
Existing validators in _validators
are merged with options.validators
to be attached by setValidator
. This should be called in the initailize
or setup
method.
Syntax:
currentClass;
Returns: Class instance.
setValidator
Set functions by property. The function will be decorated to be bound to the class instance.
Syntax:
currentClass
Arguments:
- Two Arugments:
- name - (String) Name of the validator.
- function - (Function) The validation function to test against a passed parameter.
- One Argument:
- obj - (Object) Name/function object.
Returns: Class instance.
_orig
attribute.
Note: The original undecorated function is stored on the decorated function in the Example:
var klass = Implements: Snitch options: validators: fullName: TypeisString // Type.isString is a method in MooTools-Core that tests arguments whether they are strings or not by returning a boolean ; var currentClass = ; // manually executed because klass doesn't have an initialize or setup method to execute setupValidators.currentClass; // returns the validation functionvar fullNameValidator = currentClass; // the undecorated original functionfullNameValidator_orig;
getValidator
Retrieve a stored validation function by property name.
Syntax:
currentClass;
Arguments
- name - (String) The name of the validator to return. Consecutive names will return an object of name/function matches.
Returns:
- More than One Consecutive Argument
- (Object) Name/function pairs containing matches validator functions and their corresponding names. An unexisting validator will return
undefined
in place of the function.
- (Object) Name/function pairs containing matches validator functions and their corresponding names. An unexisting validator will return
- One argument
- (Function) Validation function corresponding to the name.
Example:
currentClass; // returns function or undefined currentClass; // returns an object containing age and fullName properties
validate
Convenient method to retrieve a validator by property to test the value against. By default it always returns true. If a validator exists, it returns the results of validation.
Syntax:
currentClass;
Arguments:
- property - (String) Name of the validator to retrieve.
- value - (Mixed) Value to validate by the retrieved validator.
Returns:
- (Boolean) Value of whether validation has passed or not.
proof
"Proof" an object where every item that exists in _validators
exists in the object and every validation function returns a true
value. This causes _validators
to act like a spec. By default, proof
returns true in case there are no defined validators. It is a convenient method that utilizes Snitch Function: proof
;
Syntax:
currentClass;
Arguments:
- obj - (Object) The object that will be tested against every validator in
_validators
. Every property in_validators
just exist in obj and every function must pass in order for proof to return true.
Returns:
- (Boolean) Value of whether the object has passed validation and item existence.
Snitch Function: proof
Generic method to proof an object with validators.
Syntax:
Snitch;
Arguments:
- obj - (Object) Object of key/value pairs that will be compared against
validators
- validators - (Object) Object of key/function pairs that will be used to compare against
obj
where each key has to exist in theobj
and theobj
property value passes the validator function.
Returns:
- (Boolean) Value of whether the object has passed validation and item existence.