[Go to site: main page, start]

Class ActiveEffectTypeDataModel

A TypeDataModel for ActiveEffects. A single ArrayField is defined for EffectChangeData. A system can override the changes SchemaField but must preserve definitions for type, phase, and priority.

Hierarchy (View Summary)

Index

Constructors

Properties

_source: object

The source data object for this DataModel instance. Once constructed, the source object is sealed such that no keys may be added nor removed.

parent: DataModel<object, DataModelConstructionContext> | null

An immutable reverse-reference to a parent DataModel to which this model belongs.

The defined and cached Data Schema for all instances of this DataModel.

LOCALIZATION_PREFIXES: any[] = []

A set of localization prefix paths which are used by this DataModel. This provides an alternative to defining the label and hint property of each field by having foundry map the labels to a structure inside the path provided by the prefix.

JavaScript class definition and localization call.

class MyDataModel extends foundry.abstract.DataModel {
static defineSchema() {
return {
foo: new foundry.data.fields.StringField(),
bar: new foundry.data.fields.NumberField()
};
}
static LOCALIZATION_PREFIXES = ["MYMODULE.MYDATAMODEL"];
}

Hooks.on("i18nInit", () => {
// Foundry will attempt to automatically localize models registered for a document subtype, so this step is only
// needed for other data model usage, e.g. for a Setting.
Localization.localizeDataModel(MyDataModel);
});

JSON localization file

{
"MYMODULE": {
"MYDATAMODEL": {
"FIELDS" : {
"foo": {
"label": "Foo",
"hint": "Instructions for foo"
},
"bar": {
"label": "Bar",
"hint": "Instructions for bar"
}
}
}
}
}

Accessors

  • get invalid(): boolean

    Is the current state of this DataModel invalid? The model is invalid if there is any unresolved failure.

    Returns boolean

Methods

  • Traverse the data model instance, obtaining the DataField definition for a field of a particular property.

    Parameters

    • key: string | string[]

      A property key like ["abilities", "strength"] or "abilities.strength"

    Returns DataField | undefined

    The corresponding DataField definition for that field, or undefined

  • Specific callback actions to take when the embedded HTML for this Document has been added to the DOM.

    Parameters

    • element: HTMLDocumentEmbedElement

      The embedded document HTML

    Returns void

  • Prepare data related to this DataModel itself, before any derived data (including Active Effects) is computed. This is especially useful for initializing numbers, arrays, and sets you expect to be modified by active effects.

    Called before ClientDocument#prepareBaseData in ClientDocument#prepareData.

    Returns void

    prepareBaseData() {
    // Ensures an active effect of `system.encumbrance.max | ADD | 10` doesn't produce `NaN`
    this.encumbrance = {
    max: 0
    }
    // If you need to access the owning Document, `this.parent` provides a reference for properties like the name
    // or embedded collections, e.g. `this.parent.name` or `this.parent.items`
    }
  • Apply transformations or derivations to the values of the source data object. Compute data fields whose values are not stored to the database.

    Called before ClientDocument#prepareDerivedData in ClientDocument#prepareData.

    Returns void

    prepareDerivedData() {
    this.hp.bloodied = Math.floor(this.hp.max / 2);

    // this.parent accesses the Document, allowing access to embedded collections
    this.encumbrance.value = this.parent.items.reduce((total, item) => {
    total += item.system.weight;
    return total;
    }, 0)
    }
  • Reset the state of this data instance back to mirror the contained source data, erasing any changes.

    Returns void

  • Convert this Document to some HTML display for embedding purposes.

    Parameters

    • config: DocumentHTMLEmbedConfig

      Configuration for embedding behavior.

    • Optionaloptions: any = {}

      The original enrichment options for cases where the Document embed content also contains text that must be enriched.

    Returns Promise<any>

  • Extract the source data for the DataModel into a simple object format that can be serialized.

    Returns object

    The document source data expressed as a plain object

  • Copy and transform the DataModel into a plain object. Draw the values of the extracted object from the data source (by default) otherwise from its transformed values.

    Parameters

    • Optionalsource: boolean = true

      Draw values from the underlying data source rather than transformed values

    Returns object

    The extracted primitive object

  • Update the DataModel locally by applying an object of changes to its source data. The provided changes are expanded, cleaned, validated, and stored to the source data object for this model. The provided changes argument is mutated in this process. The source data is then re-initialized to apply those changes to the prepared data. The method returns an object of differential changes which modified the original data.

    Parameters

    • changes: object = {}

      New values which should be applied to the data model

    • options: DataModelUpdateOptions = {}

      Options which determine how the new data is merged

    Returns object

    An object containing differential keys and values that were changed

    An error if the requested data model changes were invalid

  • Validate the data contained in the document to check for type and content. This method is intended to validate complete model records, verifying both individual field validation as well as joint model validity.

    For validating sets of partial model changes, it is preferred to call DataModel#updateSource as a dryRun. This method provides a convenience alias for such a workflow if changes are provided.

    Warning: if fallback handling is allowed, this process will mutate provided changes or model source data.

    Parameters

    Returns boolean

    Whether the data source or proposed change is reported as valid. A boolean is always returned if validation is non-strict.

    An error thrown if validation is strict and a failure occurs.

  • Protected

    Configure the data model instance before validation and initialization workflows are performed.

    Parameters

    • Optionaloptions: object = {}

      Additional options modifying the configuration

    Returns void

  • Protected

    Resolve a previously-initialized embedded DataModel that corresponds to an element being cleaned. Called during recursive data cleaning when a parent field contains EmbeddedDataField elements, or a single nested DataModel field (such as a TypeDataField), in order to propagate the inner DataModel into _state.model for the recursive clean operation. A single (non-collection) inner model resolves to itself; collection elements are matched by stable _id when one is present, otherwise by positional index.

    Subclasses may override when data preparation reshapes the field property in a way that the default cannot interpret, for example wrapping the container in a non-iterable type or replacing it with a derived view.

    Parameters

    • field: DataField

      The schema field being recursed into.

    • element: { index?: number; value: object } = {}
      • Optionalindex?: number

        The positional index of the element within a container, if applicable.

      • value: object

        The cleaned candidate value for the element being processed.

    • Optionaloptions: Readonly<DataModelCleaningOptions> = {}

      The cleaning options in effect for the operation.

    Returns DataModel<object, DataModelConstructionContext> | null

    The corresponding previously-initialized inner DataModel, or null.

  • Protected

    A generator that orders the DataFields in the DataSchema into an expected initialization order.

    Returns Generator<[string, DataField], any, any>

  • Protected

    Initialize the instance by copying data from the source object to instance attributes. This mirrors the workflow of SchemaField#initialize but with some added functionality.

    Parameters

    • Optionaloptions: object = {}

      Options provided to the model constructor

    Returns void

  • Protected

    Called by ClientDocument#_onCreate.

    Parameters

    • data: object

      The initial data object provided to the document creation request

    • options: object

      Additional options which modify the creation request

    • userId: string

      The id of the User requesting the document update

    Returns void

  • Protected

    Called by ClientDocumentMixin#_onDelete.

    Parameters

    • options: object

      Additional options which modify the deletion request

    • userId: string

      The id of the User requesting the document update

    Returns void

  • Protected

    Called by ClientDocumentMixin#_onUpdate.

    Parameters

    • changed: object

      The differential data that was changed relative to the documents prior values

    • options: object

      Additional options which modify the update request

    • userId: string

      The id of the User requesting the document update

    Returns void

  • Protected

    Called by ClientDocument#_preCreate.

    Parameters

    • data: object

      The initial data object provided to the document creation request

    • options: object

      Additional options which modify the creation request

    • user: BaseUser

      The User requesting the document creation

    Returns Promise<boolean | void>

    Return false to exclude this Document from the creation operation

  • Protected

    Called by ClientDocumentMixin#_preDelete.

    Parameters

    • options: object

      Additional options which modify the deletion request

    • user: BaseUser

      The User requesting the document deletion

    Returns Promise<boolean | void>

    A return value of false indicates the deletion operation should be cancelled.

  • Protected

    Called by ClientDocumentMixin#_preUpdate.

    Parameters

    • changes: object

      The candidate changes to the Document

    • options: object

      Additional options which modify the update request

    • user: BaseUser

      The User requesting the document update

    Returns Promise<boolean | void>

    A return value of false indicates the update operation should be cancelled.

  • Protected

    Perform the second step of the DataModel#_updateSource workflow which applies the prepared diff to the model.

    Parameters

    • copy: object

      The prepared copy of source data with changes applied

    • diff: object

      The differential changes that were applied to source

    • options: DataModelUpdateOptions

      Options which determine how the new data is merged

    • _state: data.types.DataModelUpdateState

      Data cleaning state which might include instructions for final commit

    Returns void

  • Protected

    Perform the first step of the DataModel#_updateSource workflow which applies changes to a copy of model source data and records the resulting diff.

    Parameters

    • copy: object

      A mutable copy of model source data

    • changes: object

      New values which should be applied to the data model

    • options: DataModelUpdateOptions

      Options which determine how the new data is merged

    • _state: data.types.DataModelUpdateState

      Data cleaning state

    Returns object

    The resulting difference applied to source data

    A failure if the proposed change is invalid

  • Migrate candidate source data for this DataModel which may require initial cleaning or transformations.

    Parameters

    • source: object

      Candidate source data for the module, before further cleaning

    • Optionaloptions: Readonly<DataModelCleaningOptions>

      Additional options for how the field is cleaned

    Returns object

    Migrated source data, ready for further cleaning

  • Wrap data migration in a try/catch which attempts it safely.

    Parameters

    • source: object

      Candidate source data for the module, before further cleaning

    • Optionaloptions: Readonly<DataModelCleaningOptions> = {}

      Additional options for how the field is cleaned

    Returns object

    Migrated source data, ready for further cleaning

  • Take data which conforms to the current data schema and add backwards-compatible accessors to it in order to support older code which uses this data.

    Parameters

    • data: object

      Data which matches the current schema

    • Optionaloptions: { embedded?: boolean } = {}

      Additional shimming options

      • Optionalembedded?: boolean

        Apply shims to embedded models?

    Returns object

    Data with added backwards-compatible properties, which is the same object as the data argument

  • Evaluate joint validation rules which apply validation conditions across multiple fields of the model. Field-specific validation rules should be defined as part of the DataSchema for the model. This method allows for testing aggregate rules which impose requirements on the overall model.

    Parameters

    • data: object

      Candidate data for the model

    Returns void

    An error if a validation failure is detected

  • Protected

    Apply final custom model-specific cleaning rules after data schema fields are cleaned. Subclass models can implement this function as an ideal place to apply custom imputation or cleaning. Cleaning must be done in-place rather than returning a different object.

    Parameters

    Returns object

    The original data object, with cleaning performed inplace