Model Class
The model Object that wraps the JSON.
Constructor
Model
-
json?
-
metadata?
Parameters:
-
json?
ObjectThe json object to be modeled.
-
metadata?
ObjectMay contain the following: name - name of the Model, defaults to "root" *plus any properties accepted by the createProperty method metadata argument or additional data you want stored in the metadata.
Example:
For examples see: testPrimitiveSaveLoad, testObjectsSaveLoad, testComplexSaveLoad testGetNameMethod and testSaveLoadWithMetaData
Item Index
Methods
- clone
- connect static
- createProperty
- destroy
- endTransaction static
- find static
- getFormattedValue
- getMetadata
- getName
- getShortName
- getValue
- hasValidator
- inTransaction static
- isArray static
- merge
- noConflict static
- off
- on
- onChange
- setValue
- startTransaction static
- toJSON
- trigger
- validateValue
Properties
- asyncEvents static
- Event.ALL static
- Event.CHANGE static
- Event.CHILD_CREATED static
- Event.CHILD_DESTROYED static
- Event.DESTROY static
- Event.MODEL_CHANGE static
- Event.PROPERTY_CHANGE static
- Formatter static
- isLoggingEnabled static
- TRANSACTION_OPTIONS.fireOnlyMostRecentPropertyEvent static
- TRANSACTION_OPTIONS.flattenCallbacks static
- TRANSACTION_OPTIONS.flattenCallbacksByHash static
- TRANSACTION_OPTIONS.suppressAllEvents static
Methods
clone
()
Model
Clones the Model rooted at this keeping all metadata that exist, but not keeping any event listeners. The name of all properties are adjusted to reflect it's new root.
Returns:
Example:
var newModel = model.clone(); // clone root model
var clonedSubModel = model.subModel.clone(); // clone subModel
For more examples: testModelClone
connect
-
src
-
dest
-
options?
Connects two properties together. So that events fired on one are also fired on the other. The options specifies the type of connection to create.
Parameters:
-
src
[Property]The source Property
-
dest
[Property]The destination Property
-
options?
ObjectA hash of options describing how to connect the two properties. The following option are accepted:
- eventBlackList {Array} - A array of eventNames that should not be connected between the two Properties, all other event are connected.
- eventWhiteList {Array} - A array of eventNames that should be connected between the two Properties, all other events not connected.
- includeChildred {boolean} - Indicates if we should connect all the children of source Property as well. The default is false.
- mapFunction {function} - A function that will map PropertyNames in 'a' to propertyNames in 'b' that should be connected. If the function returns null, the property won't be connected to anything. *This option must be used in conjunction with includeChildren=true. If not specified the default behavior is to map all properties via the getName function. Thus only properties with the same name are connected
- direction {"oneWay"|"dual"} - Specifies how you would like to connect the two Properties. If not specified default is "dual".
Returns:
createProperty
-
name
-
value
-
metadata?
-
suppressNotifications?
Creates the property with the given name on this. This will fire the childCreated event on the parent. The metadata can contain custom keys or any of the special keys below.
Parameters:
-
name
StringName of the property
-
value
String, Boolean, Number, null, Date, Function, ObjectProperty value
-
metadata?
ObjectA hash of metadata associated with the property. You can put any metadata you want. However the following keys have special meaning and are reserved for use by the framework.
- validator {Function} - a function to validate if the new value is valid before it is assigned.
- Formatter {Function} - a function that takes this.getValue() as input and output the value you want returned by the getFormattedValue function. See the documentation of getFormattedValue for more details.
- url {String} - the resource this model should use to get it's value. Resource must return json. Must be used with refreshRate
- refreshRate {Number} - the interval used to query the url for changes. must be > 100 or -1. -1 indicates to only fetch value once. Must be used with url
- isJSONPurl {Boolean} - if true will use JSONP to fetch the data. The url provided must have the string "$jsonpCallback" where the jsonp callback function should be inserted.
- doNotPersist {Boolean} - property will not exist in the json object returned by the toJSON method.
- doNotPersistValue {Boolean} - will clear the value of the property when toJSON is called. For Object and Array types the value will be and empty object/array. Else it will be undefined. *Note metadata can still be persisted.
- thin {Boolean} - will create a model property representing this but not model any of it's children properties
-
suppressNotifications?
Booleanindicates if listeners should be notified of change.
Returns:
Example:
var model = new Model();
model.createProperty("number", 1) // a simple property (model.number)
.createProperty("subModel", { // a property that is a subModel (model.subModel and model.subModel.str)
str: "stringProperty"
})
.createProperty("positiveNumber", 2, { // a property with a positiveNumber validator and a custom attribute
validator: function (value) {
return value > 0;
},
customMetadata: "this Property is special"
}),
.createProperty ("remoteModel", {prop1: "defaultValue"}, { // a remote model populated via the twitter rest api.
url: "http://search.twitter.com/search.json?q=tennis&callback=$jsonpCallback",
doNotPersist: true,
refreshRate: -1, // -1 means fetch once.
isJSONPurl: true
}); // Note the method chaining.
For examples see: testModelCreationUsingCreatePropertyMethod, testThinModel
destroy
-
suppressNotifications?
Removes the property and its children if any from the Model. This will fire the 'destroy' event on this and the 'childDestroyed' event on the parent for every Property in the Model.
Parameters:
-
suppressNotifications?
Booleanindicates if listeners should be notified of destroy.
Returns:
endTransaction
-
options?
Ends the current transaction causing all queued up events to be fired according to the global eventOptization settings or the settings passed in if they exist.
Parameters:
-
options?
ObjectA map of Model.TRANSACTION_OPTIONS options that you want overridden when clearing this transaction queue.
Example:
model.endTransaction(); //uses settings found in Model.TRANSACTION_OPTIONS
model.endTransaction({ // override the Model.TRANSACTION_OPTIONS settings for this transaction
fireOnlyMostRecentPropertyEvent: false,
flattenCallbacks: true,
flattenCallbacksByHash: true
})
For more examples see: testFlattenCallbacks, testFlattenCallbacksByHash, testModelEndTransactionWithOptions
find
-
model
-
propertyName
Searches the given model for the property of the given name and returns it.
Parameters:
-
model
Property, Model, ArrayPropertyThe model to search.
-
propertyName
StringThe fully qualified name of the property. Equal to the getName() value.
Returns:
getFormattedValue
()
Any
Return the formatted value calculated by passing this.getValue() to the this.getMetadata().Formatter function if it exists. If the metadata Formatter does not exist it will fall back to the global Formatter located at Model.Formatter. If that does not exist it will return this.getValue();
Returns:
getMetadata
()
Object
Retrieves the metadata associated with this. The metadata is persisted with the json when you pass true to the toJSON method (eg. this.toJSON(true)). Likewise the metadata will be restored when creating a model from the very same json. Note: the modeljs framework uses the metadata to store attributes associated the properties that is uses. As a result the following keys have special meaning. [validator, Formatter, name, url, refreshRate, isJSONPurl, doNotPersist, doNotPersistValue, thin]
For example see: testGetMetadataMethod
Returns:
getName
()
String
The fully qualified name of this. The name is calculated by concatenating the name of the parent, "/", and name of this AKA the shortName. To create a named root pass in the name option key to the Model Constructor.
Returns:
Example:
defaultModel.getName(); // returns "/root"
defaultModel.property1.getName(); // returns "/root/property1"
namedRoot.property1.getName(); // returns "/customName/property1"
For more examples see: testGetNameMethod
getShortName
()
String
The given name of the property.
Returns:
getValue
()
Object
Gets the value associated with the Model. This will be a json Object.
Returns:
hasValidator
()
Boolean
Determine if this has a validation function associated with it.
Returns:
Example:
For examples see: testPropertyValidationFunction
inTransaction
()
Boolean
static
Determines if you are currently in a start/end transaction block.
Returns:
Example:
For an examples see testModelTransactions
isArray
-
property
Determines if the parameter passed in is an modeljs Array Property.
Parameters:
-
property
PropertyProperty to test whether or not it is an Array Property.
Returns:
merge
-
json
-
keepOldProperties?
-
suppressNotifications?
Preforms the merge operation on this. The merge operation will add properties that exist in the merged object but not in this, remove those that are not found in the merged object (unless keepOldProperties is set to true) and will call setValue for those that exist in both. Note the operation will log an error to the console, return false, and not modify the object if any of the setValue operation are not valid. Not valid set operations included those that try to set a value from a property to a model and vise versa.
Parameters:
-
json
ObjectThe json object to have merged.
-
keepOldProperties?
BooleanTrue if you want to keep properties that exist in this but not in the passed in json, Otherwise they will be deleted. Defaults to false.
-
suppressNotifications?
Booleanindicates if listeners should be notified of change.
Returns:
Example:
For an example see: testModelMergeMethod
noConflict
()
[Model]
static
Release control of the global window.Model variable restoring it to its previous value
Returns:
Example:
// window.Model is restore to previous value and localModel now holds the window.Model reference
var localModel = window.Model.noConflict();
For an example see testModelNoConflict
off
-
events
-
callback?
Removes all instances of the given callback on the given events on this.
Parameters:
-
events
StringOne or more space separated eventNames
-
callback?
FunctionThe function to remove. if not specified all callbacks are removed
Returns:
on
-
events
-
callback
Registers the given callback with the given events on this. When the callback is executed it will have it's 'this' context bound to this (ie. the property listening to the event). The first argument will be the property that triggered the event. In most cases these are the same property, unless the event is bubbling up the tree. The final argument is optional and varies depending on event type.
Parameters:
-
events
StringOne or more space separated eventNames
-
callback
FunctionThe function to execute when the given event is triggered
Returns:
onChange
-
callback
-
listenToChildren?
Registers a callback function with the change event of this. When the callback is executed it will have it's 'this' context bound to this (ie. the property listening to the event). The first argument will be the property that triggered the event. The final argument be the oldValue before it was changed.
Parameters:
-
callback
FunctionThe function to be called if the value of this changes. The callback function will be passed the following arguments (oldValue, newValue, propertyName)
-
listenToChildren?
BooleanRegisters the callback with sub property changes as well.
Example:
model.onChange(callback, {listenToChildren: true}); //listens to change events on entire model
model.property1.onChange(callback) //listen to change on property1 only
model.subModel.onChange(callback) //listen to change on subModel only. (ie. via model.subModel.setValue(..))
For more examples see: testOnChangeCallbackWhenSettingToSameValue and testBubbleUpEvents
setValue
-
newValue
-
suppressNotifications?
Called to set the value of a model. If the setValue is the same as the current value, nothing will happen and no change events will be fired. If the value is different it must pass the validator if there is one. If it does pass the validator and the value is changed, all registered listeners will be notified unless the suppressNotifications option indicates otherwise.
Parameters:
-
newValue
ObjectThe Value you want to assign to this.
-
suppressNotifications?
Booleanindicates if listeners should be notified of change.
Returns:
startTransaction
()
static
Begins a transaction. All events will be put into the queued. To be fired when endTransaction is called.
Example:
For an examples see testModelTransactions
toJSON
-
includeMetaData?
Retrieves the json representation of this. This json representation can be used in the Model Constructor to recreate the same Model object. If you use includeMetaData validator metadata will be included. Properties that have the doNotPersist flag in it's metadata will have it's value nullified. This means properties will have the value set to 'undefined' while models will be set to an empty object ({}).
Parameters:
-
includeMetaData?
Booleanindicates if model meta data should be included in the returned JSON. Defaults to false.
Returns:
Example:
For an example see: testSaveLoadWithMetaData and testDoNotPersist
trigger
-
eventName
-
...eventArgs?
Triggers the given event on this. Passing the optional argument.
Parameters:
-
eventName
StringThe name of the event.
-
...eventArgs?
AnyAny number of additional parameters to pass to the registered event callback
Returns:
validateValue
-
value
Determines if the given value will pass the validation function of this.
Parameters:
-
value
ObjectA value to test against the validation function if it exists.
Returns:
Example:
For examples see: testPropertyValidationFunction
Properties
asyncEvents
Boolean Indicates if event notify listener asynchronously
static
Determines if Events notify listener asynchronously.
Default: true
Event.ALL
String
static
A special pseudo event named "all" that equivalent to listening to all 'real' events. All events are considered 'real' except for the MODEL_CHANGE event which is a special propagation event and the CHANGE event which is a pseudo event. Triggering the ALL event does not fire all event, but fires an event named all which will call all callbacks registered to the ALL event. The callback will have the following arguments:
- this = the property listening to the event
- arg[0-..n-1] = the same arguments passed to the original event
- arg[n-1] = the original event name
Event.CHANGE
String
static
The CHANGE event is pseudo event equivalent to a PROPERTYCHANGE and MODELCHANGE event. It is the event used when registering a listener using the onChange(callback, true) method. The callback will have the following arguments:
- this = the property listening to the event
- arg[0] = the property in it's current state
- arg[1] = the old value.
Event.CHILD_CREATED
String
static
The CHILDCREATED event is triggered when a new property is created. It's triggered on the parent and propagates a MODELCHANGE event up the model tree. The callback will have the following arguments:
- this = the parent property
- arg[0] = the created property
- arg[1] = undefined
Event.CHILD_DESTROYED
String
static
The CHILDDestroyed event is triggered when a child property is destroyed. It triggered on the parent and propergates a MODELCHANGE event up the model tree. The callback will have the following arguments:
- this = the parent property
- arg[0] = the destroyed property
- arg[1] = undefined
Event.DESTROY
String
static
The DESTROY event is triggered when destroy() method called on a property. It than triggers a CHILD_DESTROYED event on it's parent. The callback will have the following arguments:
- this = the destroyed property
- arg[0] = the destroyed property
- arg[1] = the old value.
Event.MODEL_CHANGE
Unknown
static
The MODEL_CHANGE event is triggered when the value of any of the property's children have changed. This includes child properties being created or destroyed. When triggered on a property it will bubble the event up it's model tree. The callback will have the following arguments:
- this = the property listening to the event. (or is registered with the callback)
- arg[0] = the property that triggered the modelChange
- arg[1] = the old value.
Event.PROPERTY_CHANGE
String
static
The PROPERTYCHANGE event is triggered only when the value of the property has changed via setValue. When triggered it will bubble up a MODELCHANGED event. Listen to this event if you only want to be notified of direct changes to the property and not changes to any of it's children. This is what the onChange(callback, false) does. PROPERTY_CHANGE event callbacks will be called with the following arguments:
- this = the property listening to the event
- arg[0] = the property in it's current state
- arg[1] = the old value.
Formatter
Function A format function whose first argument is the value to be formatted
static
A global formatter used to calculate the formatted value of a Property. If defined the function will be called when getFormattedValue gets called. The function should accept the value to be formatted as the first argument and expect 'this' to be the Property. The formatter must be able to handle any input type as a value.
Example:
Model.Formatter = function (value) { //makes all strings uppercase
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
}
isLoggingEnabled
Boolean Indicates if Logging is enabled
static
If logging is enabled any warning or incorrect uses of the api will result in output to the console if it exists.
Default: false
TRANSACTION_OPTIONS.fireOnlyMostRecentPropertyEvent
Boolean
static
Only fires the last event of a property during a transaction.
Default: false
Example:
For an example see testFireOnlyMostRecentPropertyEvent
TRANSACTION_OPTIONS.flattenCallbacks
Boolean
static
Will make sure a callback only gets called only once during a transaction. Even if registered with several properties.
Default: false
Example:
For an example see testFlattenCallbacks
TRANSACTION_OPTIONS.flattenCallbacksByHash
Boolean
static
Will make sure callbacks identified by .hash only gets called only once during a transaction. Even if registered with several properties.
Default: false
Example:
For an example see testFlattenCallbacksByHash
TRANSACTION_OPTIONS.suppressAllEvents
Boolean
static
Will guarantee that no event are fired during a transaction
Default: false
Example:
For an example see testSuppressAllEvents