API Docs for: 2.1.2
Show:

Model Class

Extends Property
Defined in: src\model.js:993
Module: Model

The model Object that wraps the JSON.

Constructor

Model

(
  • json?
  • metadata?
)

Defined in src\model.js:993

Parameters:

  • json? Object

    The json object to be modeled.

  • metadata? Object

    May 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

Methods

clone

() Model

Defined in src\model.js:1275

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:

Model: Returns a new Model object rooted at this, keeping any metadata but no event listeners.

Example:

var newModel = model.clone(); // clone root model
var clonedSubModel = model.subModel.clone(); // clone subModel

For more examples: testModelClone

connect

(
  • src
  • dest
  • options?
)
Function static

Defined in src\model.js:1500

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? Object

    A 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:

Function: The disconnect function. When executed will remove the connection between the properties.

createProperty

(
  • name
  • value
  • metadata?
  • suppressNotifications?
)
Model

Defined in src\model.js:1185

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 String

    Name of the property

  • value String, Boolean, Number, null, Date, Function, Object

    Property value

  • metadata? Object

    A 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? Boolean

    indicates if listeners should be notified of change.

Returns:

Model: Returns this for method chaining

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?
)
Property

Inherited from Property but overwritten in src\model.js:1254

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? Boolean

    indicates if listeners should be notified of destroy.

Returns:

Property: The deleted Property.

endTransaction

(
  • options?
)
static

Defined in src\model.js:1661

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? Object

    A 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
)
Property, Model, ArrayProperty static

Defined in src\model.js:1452

Searches the given model for the property of the given name and returns it.

Parameters:

  • model Property, Model, ArrayProperty

    The model to search.

  • propertyName String

    The fully qualified name of the property. Equal to the getName() value.

Returns:

Property, Model, ArrayProperty: The model object of the given name, null otherwise.

getFormattedValue

() Any

Inherited from Property: src\model.js:520

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:

Any: The formatted Value

getMetadata

() Object

Inherited from Property: src\model.js:760

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:

Object: A map of metadata properties associated with this.

getName

() String

Inherited from Property: src\model.js:539

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:

String: The fully qualified name of this.

Example:

defaultModel.getName();              // returns "/root"
defaultModel.property1.getName();    // returns "/root/property1"
namedRoot.property1.getName();       // returns "/customName/property1"

For more examples see: testGetNameMethod

getShortName

() String

Inherited from Property: src\model.js:561

The given name of the property.

Returns:

String: The given name of the property.

getValue

() Object

Inherited from Property but overwritten in src\model.js:1061

Gets the value associated with the Model. This will be a json Object.

Returns:

Object: The json Object represented by the model

hasValidator

() Boolean

Inherited from Property: src\model.js:777

Determine if this has a validation function associated with it.

Returns:

Boolean: True if this has a validator associated with it. False otherwise.

Example:

For examples see: testPropertyValidationFunction

inTransaction

() Boolean static

Defined in src\model.js:1696

Determines if you are currently in a start/end transaction block.

Returns:

Boolean: True if your in a transaction block, false otherwise.

Example:

For an examples see testModelTransactions

isArray

(
  • property
)
Boolean static

Defined in src\model.js:1041

Determines if the parameter passed in is an modeljs Array Property.

Parameters:

  • property Property

    Property to test whether or not it is an Array Property.

Returns:

Boolean: true if the Property is an Array Property, false otherwise

merge

(
  • json
  • keepOldProperties?
  • suppressNotifications?
)
Boolean

Defined in src\model.js:1342

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 Object

    The json object to have merged.

  • keepOldProperties? Boolean

    True 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? Boolean

    indicates if listeners should be notified of change.

Returns:

Boolean: Returns true if merge was successful, false otherwise.

Example:

For an example see: testModelMergeMethod

noConflict

() [Model] static

Defined in src\model.js:1873

Release control of the global window.Model variable restoring it to its previous value

Returns:

[Model]: The window Model variable that was just released.

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?
)
Property

Inherited from Property: src\model.js:730

Removes all instances of the given callback on the given events on this.

Parameters:

  • events String

    One or more space separated eventNames

  • callback? Function

    The function to remove. if not specified all callbacks are removed

Returns:

Property: Returns this for Object chaining.

on

(
  • events
  • callback
)
Property

Inherited from Property: src\model.js:700

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 String

    One or more space separated eventNames

  • callback Function

    The function to execute when the given event is triggered

Returns:

Property: Returns this for Object chaining.

onChange

(
  • callback
  • listenToChildren?
)

Inherited from Property: src\model.js:608

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 Function

    The function to be called if the value of this changes. The callback function will be passed the following arguments (oldValue, newValue, propertyName)

  • listenToChildren? Boolean

    Registers 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?
)
this

Inherited from Property but overwritten in src\model.js:1088

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 Object

    The Value you want to assign to this.

  • suppressNotifications? Boolean

    indicates if listeners should be notified of change.

Returns:

this: this for method chaining.

startTransaction

() static

Defined in src\model.js:1645

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?
)
Object

Defined in src\model.js:1377

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? Boolean

    indicates if model meta data should be included in the returned JSON. Defaults to false.

Returns:

Object: The json representation of the Model.

Example:

For an example see: testSaveLoadWithMetaData and testDoNotPersist

trigger

(
  • eventName
  • ...eventArgs?
)
Property

Inherited from Property: src\model.js:684

Triggers the given event on this. Passing the optional argument.

Parameters:

  • eventName String

    The name of the event.

  • ...eventArgs? Any

    Any number of additional parameters to pass to the registered event callback

Returns:

Property: Returns this for Object chaining.

validateValue

(
  • value
)
Boolean

Inherited from Property but overwritten in src\model.js:1124

Determines if the given value will pass the validation function of this.

Parameters:

  • value Object

    A value to test against the validation function if it exists.

Returns:

Boolean: The result of passing value against the validation function if it exists. True otherwise.

Example:

For examples see: testPropertyValidationFunction

Properties

asyncEvents

Boolean Indicates if event notify listener asynchronously static

Defined in src\model.js:1712

Determines if Events notify listener asynchronously.

Default: true

Event.ALL

String static

Defined in src\model.js:1812

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

Defined in src\model.js:1756

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

Defined in src\model.js:1784

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

Defined in src\model.js:1798

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

Defined in src\model.js:1770

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

Defined in src\model.js:1742

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

Defined in src\model.js:1726

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

Defined in src\model.js:1418

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

Defined in src\model.js:1441

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

Defined in src\model.js:1832

Only fires the last event of a property during a transaction.

Default: false

Example:

For an example see testFireOnlyMostRecentPropertyEvent

TRANSACTION_OPTIONS.flattenCallbacks

Boolean static

Defined in src\model.js:1841

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

Defined in src\model.js:1850

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

Defined in src\model.js:1859

Will guarantee that no event are fired during a transaction

Default: false

Example:

For an example see testSuppressAllEvents