API Docs for: 0.7.5
Show:

Data.common.data Class

Access point: ac.data.*

A model for getting and setting data that is shared by a single mojit controller, binder, and/or template.

See also https://developer.yahoo.com/cocktails/mojito/docs/topics/mojito_data.html#sharing-data

Methods

_parse

(
  • response
)
Object protected

Calls the public, overrideable parse() method and returns the result.

Override this method to provide a custom pre-parsing implementation. This provides a hook for custom persistence implementations to "prep" a response before calling the parse() method.

Parameters:

  • response Any

    Server response.

Returns:

Object: Attribute hash.

_validate

(
  • attributes
  • callback
)
protected

TODO: Update method description.

Calls the public, overridable validate() method and fires an error event if validation fails.

Parameters:

  • attributes Object

    Attribute hash.

  • callback Function

    Validation callback.

    • [err] Any optional

      Value on failure, non-value on success.

addAttr

(
  • name
  • config
  • lazy
)
Object protected chainable

Duckpunches the addAttr method provided by Y.Attribute to keep the id attribute’s value and a custom id attribute’s (if provided) value in sync when adding the attributes to the model instance object.

Marked as protected to hide it from Model's public API docs, even though this is a public method in Attribute.

Parameters:

  • name String

    The name of the attribute.

  • config Object

    An object with attribute configuration property/value pairs, specifying the configuration for the attribute.

  • lazy Boolean

    (optional) Whether or not to add this attribute lazily (on the first call to get/set).

Returns:

Object: A reference to the host object.

enableHookGroup

(
  • handler
  • group
)

Enable a group for a request.

Parameters:

  • handler Object

    A placeholder for a collection of hooks enabled during the runtime. Usually req.hook or adapter.hook object.

  • group String

    The name of the group to enable

    Example:

    Y.mojito.hooks.enableHookGroup(req.hook, 'test_group');
    

generateClientId

() String

Returns a clientId string that's unique among all models on the current page (even models in other YUI instances). Uniqueness across pageviews is unlikely.

Returns:

String: Unique clientId.

get

(
  • name
)
Any

Returns the value of the specified attribute.

If the attribute's value is an object, name may use dot notation to specify the path to a specific property within the object, and the value of that property will be returned.

Parameters:

  • name String

    Attribute name or object property path.

Returns:

Any: Attribute value, or undefined if the attribute doesn't exist.

Example:

// Set the 'foo' attribute to an object.
myModel.set('foo', {
    bar: {
        baz: 'quux'
    }
});

// Get the value of 'foo'.
myModel.get('foo');
// => {bar: {baz: 'quux'}}

// Get the value of 'foo.bar.baz'.
myModel.get('foo.bar.baz');
// => 'quux'

getAsHTML

(
  • name
)
String

Returns an HTML-escaped version of the value of the specified string attribute. The value is escaped using Y.Escape.html().

Parameters:

  • name String

    Attribute name or object property path.

Returns:

String: HTML-escaped attribute value.

getAsURL

(
  • name
)
String

Returns a URL-encoded version of the value of the specified string attribute. The value is encoded using the native encodeURIComponent() function.

Parameters:

  • name String

    Attribute name or object property path.

Returns:

String: URL-encoded attribute value.

hook

(
  • name
  • handler
  • hook
)

Shim for the hooks trigger mechanism. Under normal conditions the shim will do nothing, but if there is at least one hook registered, and enabled, it will try to proces the hook.

Parameters:

  • name String

    The name of the hook.

  • handler Object

    A placeholder for a collection of hooks enabled during the runtime. Usually req.hook or adapter.hook object.

  • hook Object

    specific data

    Example:

    Y.mojito.hooks.hook('test_hook', ctx, ...);
    

isModified

() Boolean

Returns true if any attribute of this model has been changed since the model was last saved.

New models (models for which isNew() returns true) are implicitly considered to be "modified" until the first time they're saved.

Returns:

Boolean: true if this model has changed since it was last saved, false otherwise.

isNew

() Boolean

Returns true if this model is "new", meaning it hasn't been saved since it was created.

Newness is determined by checking whether the model's id attribute has been set. An empty id is assumed to indicate a new model, whereas a non-empty id indicates a model that was either loaded or has been saved since it was created.

Returns:

Boolean: true if this model is new, false otherwise.

load

(
  • [options]
  • [callback]
)
chainable

Loads this model from the server.

This method delegates to the sync() method to perform the actual load operation, which is an asynchronous action. Specify a callback function to be notified of success or failure.

A successful load operation will fire a load event, while an unsuccessful load operation will fire an error event with the src value "load".

If the load operation succeeds and one or more of the loaded attributes differ from this model's current attributes, a change event will be fired.

Parameters:

  • [options] Object optional

    Options to be passed to sync() and to set() when setting the loaded attributes. It's up to the custom sync implementation to determine what options it supports or requires, if any.

  • [callback] Callback optional

    Called when the sync operation finishes.

    • err Error | Null

      If an error occurred, this parameter will contain the error. If the sync operation succeeded, err will be null.

    • response Any

      The server's response. This value will be passed to the parse() method, which is expected to parse it and return an attribute hash.

parse

(
  • response
)
Object

Called to parse the response when the model is loaded from the server. This method receives a server response and is expected to return an attribute hash.

The default implementation assumes that response is either an attribute hash or a JSON string that can be parsed into an attribute hash. If response is a JSON string and either Y.JSON or the native JSON object are available, it will be parsed automatically. If a parse error occurs, an error event will be fired and the model will not be updated.

You may override this method to implement custom parsing logic if necessary.

Parameters:

  • response Any

    Server response.

Returns:

Object: Attribute hash.

registerhook

(
  • group
  • name
  • fn
)

A Mojito entity can register an interest in a hook. The call context for all groups will be the same for all hooks registered for a group, and it will be new and unique for each request. The params to the call back function are hook specific.

Parameters:

  • group String

    the name of the group for the hook

  • name String

    the hook name

  • fn Function

    the callback function that implements the hook logic.

    Example:

    Y.mojito.hooks.registerHook('test_group', 'test_hook', function (reg, data) {});
    

save

(
  • [options]
  • [callback]
)
chainable

Saves this model to the server.

This method delegates to the sync() method to perform the actual save operation, which is an asynchronous action. Specify a callback function to be notified of success or failure.

A successful save operation will fire a save event, while an unsuccessful save operation will fire an error event with the src value "save".

If the save operation succeeds and one or more of the attributes returned in the server's response differ from this model's current attributes, a change event will be fired.

Parameters:

  • [options] Object optional

    Options to be passed to sync() and to set() when setting synced attributes. It's up to the custom sync implementation to determine what options it supports or requires, if any.

  • [callback] Function optional

    Called when the sync operation finishes.

    • err Error | Null

      If an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, err will be null.

    • response Any

      The server's response. This value will be passed to the parse() method, which is expected to parse it and return an attribute hash.

set

(
  • name
  • value
  • [options]
)
chainable

Sets the value of a single attribute. If model validation fails, the attribute will not be set and an error event will be fired.

Use setAttrs() to set multiple attributes at once.

Parameters:

  • name String

    Attribute name or object property path.

  • value Any

    Value to set.

  • [options] Object optional

    Data to be mixed into the event facade of the change event(s) for these attributes.

    • [silent=false] Boolean optional

      If true, no change event will be fired.

Example:

model.set('foo', 'bar');

setAttrs

(
  • attributes
  • [options]
)
chainable

TODO: Update description.

Sets the values of multiple attributes at once. If model validation fails, the attributes will not be set and an error event will be fired.

Parameters:

  • attributes Object

    Hash of attribute names and values to set.

  • [options] Object optional

    Data to be mixed into the event facade of the change event(s) for these attributes.

    • [silent=false] Boolean optional

      If true, no change event will be fired.

Example:

model.setAttrs({
    foo: 'bar',
    baz: 'quux'
});

sync

(
  • action
  • [options]
  • [callback]
)

Override this method to provide a custom persistence implementation for this model. The default just calls the callback without actually doing anything.

This method is called internally by load(), save(), and destroy().

Parameters:

  • action String

    Sync action to perform. May be one of the following:

    • create: Store a newly-created model for the first time.
    • delete: Delete an existing model.
    • read : Load an existing model.
    • update: Update an existing model.
  • [options] Object optional

    Sync options. It's up to the custom sync implementation to determine what options it supports or requires, if any.

  • [callback] Function optional

    Called when the sync operation finishes.

    • err Error | Null

      If an error occurred, this parameter will contain the error. If the sync operation succeeded, err will be falsy.

    • [response] Any optional

      The server's response.

toJSON

() Object

Returns a copy of this model's attributes that can be passed to Y.JSON.stringify() or used for other nefarious purposes.

The clientId attribute is not included in the returned object.

If you've specified a custom attribute name in the idAttribute property, the default id attribute will not be included in the returned object.

Note: The ECMAScript 5 specification states that objects may implement a toJSON method to provide an alternate object representation to serialize when passed to JSON.stringify(obj). This allows class instances to be serialized as if they were plain objects. This is why Model's toJSON returns an object, not a JSON string.

See http://es5.github.com/#x15.12.3 for details.

Returns:

Object: Copy of this model's attributes.

undo

(
  • [attrNames]
  • [options]
)
chainable

Reverts the last change to the model.

If an attrNames array is provided, then only the named attributes will be reverted (and only if they were modified in the previous change). If no attrNames array is provided, then all changed attributes will be reverted to their previous values.

Note that only one level of undo is available: from the current state to the previous state. If undo() is called when no previous state is available, it will simply do nothing.

Parameters:

  • [attrNames] Array optional

    Array of specific attribute names to revert. If not specified, all attributes modified in the last change will be reverted.

  • [options] Object optional

    Data to be mixed into the event facade of the change event(s) for these attributes.

    • [silent=false] Boolean optional

      If true, no change event will be fired.

validate

(
  • attrs
  • callback
)

Override this method to provide custom validation logic for this model.

While attribute-specific validators can be used to validate individual attributes, this method gives you a hook to validate a hash of all attributes before the model is saved. This method is called automatically before save() takes any action. If validation fails, the save() call will be aborted.

In your validation method, call the provided callback function with no arguments to indicate success. To indicate failure, pass a single argument, which may contain an error message, an array of error messages, or any other value. This value will be passed along to the error event.

Parameters:

  • attrs Object

    Attribute hash containing all model attributes to be validated.

  • callback Function

    Validation callback. Call this function when your validation logic finishes. To trigger a validation failure, pass any value as the first argument to the callback (ideally a meaningful validation error of some kind).

    • [err] Any optional

      Validation error. Don't provide this argument if validation succeeds. If validation fails, set this to an error message or some other meaningful value. It will be passed along to the resulting error event.

Example:

model.validate = function (attrs, callback) {
    if (attrs.pie !== true) {
        // No pie?! Invalid!
        callback('Must provide pie.');
        return;
    }

    // Success!
    callback();
};

Properties

_allowAdHocAttrs

Boolean protected

This tells Y.Base that it should create ad-hoc attributes for config properties passed to Model's constructor. This makes it possible to instantiate a model and set a bunch of attributes without having to subclass Y.Model and declare all those attributes first.

Default: true

_isYUIModel

Boolean protected

Total hack to allow us to identify Model instances without using instanceof, which won't work when the instance was created in another window or YUI sandbox.

Default: true

changed

Object

Hash of attributes that have changed since the last time this model was saved.

Default: {}

idAttribute

String

Name of the attribute to use as the unique id (or primary key) for this model.

The default is id, but if your persistence layer uses a different name for the primary key (such as _id or uid), you can specify that here.

The built-in id attribute will always be an alias for whatever attribute name you specify here, so getting and setting id will always behave the same as getting and setting your custom id attribute.

Default: `'id'`

lastChange

Object

Hash of attributes that were changed in the last change event. Each item in this hash is an object with the following properties:

  • newVal: The new value of the attribute after it changed.
  • prevVal: The old value of the attribute before it changed.
  • src: The source of the change, or null if no source was specified.

Default: {}

lists

ModelList

Array of ModelList instances that contain this model.

When a model is in one or more lists, the model's events will bubble up to those lists. You can subscribe to a model event on a list to be notified when any model in the list fires that event.

This property is updated automatically when this model is added to or removed from a ModelList instance. You shouldn't alter it manually. When working with models in a list, you should always add and remove models using the list's add() and remove() methods.

Default: `[]`

Example:

Subscribing to model events on a list:

// Assuming list is an existing Y.ModelList instance.
list.on('*:change', function (e) {
    // This function will be called whenever any model in the list
    // fires a change event.
    //
    // e.target will refer to the model instance that fired the
    // event.
});