The Attribute utility allows you to add attributes to any class through an augmentable Attribute interface.
The interface adds get and
set methods to your class to retrieve and store attribute values, as well as
support for change events that can be used to listen for changes in attribute values.
In addition, attributes can be configured with custom getters, setters and validators, allowing the developer to normalize and validate values being stored or retrieved. Attributes can also be specified as read-only or write-once.
Getting Started
To include the source files for Attribute and its dependencies, first load the YUI seed file if you haven't already loaded it.
<script src="http://yui.yahooapis.com/3.8.0/build/yui/yui-min.js"></script>
Next, create a new YUI instance for your application and populate it with the
modules you need by specifying them as arguments to the YUI().use()
method.
YUI will automatically load any dependencies required by the modules you
specify.
<script> // Create a new YUI instance and populate it with the required modules. YUI().use('attribute', function (Y) { // Attribute is available and ready for use. Add implementation // code here. }); </script>
For more information on creating YUI instances and on the
use()
method, see the
documentation for the YUI Global Object.
Augmenting Your Class With Attribute
The Attribute class is designed to be augmented to an existing class (we'll refer to this class as the 'host' class) and adds attribute management support to it. For example, assuming you have a class constructor, `MyClass, to which you'd like to add attribute support, you can simply augment your class with Attribute, as shown below:
YUI().use("attribute", function(Y) { function MyClass() { ... } Y.augment(MyClass, Y.Attribute); });
Instances of your class will now have Attribute methods available, which your class can use to configure attributes for itself, and which users of your class can use to get and set attribute values. See the Attribute API documentation for a complete list of methods which Attribute will add to your class.
Note that in general, rather than augmenting Attribute directly, most implementations will simply extend Base, which augments Attribute, and handles attribute setup for you. Base also sets up all attributes to be lazily initialized (initialized on the first call to get or set) by default, improving performance.
Adding Attributes
Once augmented with Attribute, your class can either use the addAttrs
method to setup attributes en mass, or use the
addAttr
method, to add them individually. addAttrs
is tailored towards use by host classes, since in addition
to being able to initialize multiple attributes in one call, it also accepts an additional name/value hash, which can be used to allow the
user to define the initial value of attributes when instantiating Attribute driven classes, as shown below:
... function MyClass(userValues) { // Use addAttrs, to setup default attributes for // your class, and mixing in user provided initial values. var attributeConfig = { attrA : { // ... Configuration for attribute "attrA" ... }, attrB : { // ... Configuration for attribute "attrB" ... } }; this.addAttrs(attributeConfig, userValues); };
Users of your class now have the ability to pass attribute values to the constructor,
or set values using the set
method as shown below:
// Set initial value for attrA during instantiation var o = new MyClass({ attrA:5 }); // Set attrB later on o.set("attrB", "Hello World!");
Attribute Configuration Properties
Each attribute you add can be configured with the properties listed in the table below (all properties are optional and case-sensitive):
Property Name | Type | Description |
---|---|---|
value |
Any | The default value for this attribute |
valueFn |
Function |
A function, the return value of which is the value for the attribute. This property can be used instead of the value property for static configurations, if you need to set default values which require access to instance state ("this.something"). If both the value and valueFn properties are defined, the value returned by valueFn has precedence over the value property, unless it returns undefined, in which case the value property is used. The valueFn is passed the name of the attribute, allowing users to share valueFn implementations across attributes if required. |
getter |
Function |
Custom 'get' handler, which is invoked when the user calls Attribute's The function will be passed the currently stored value of the attribute as the first argument and the name of the attribute as the second argument. If configured, the value returned by this function will be the value returned to the user. Attribute also supports the ability to return sub-attribute values ( |
setter |
Function |
Custom 'set' handler, which is invoked when the user calls Attribute's The function will be passed the value which the user passed to the set method as the first argument and the name of the attribute as the second argument. If configured, the value returned by this function will be the value stored as the attribute value. The getter and setter can be used to normalize values on input/output for the user while storing the value in a format most effective for internal operation. Attribute also supports the ability to set sub-attribute values ( |
validator |
Function |
Validation function, which if defined, is called before the If the function returns If validation is a potentially expensive task and contains code which would be repeated in a Attribute also supports the ability to set sub-attribute values (set('a.b.c', 10)). The 'validator' implications for this are discussed in the Getters, Setters, Validators and Sub Attributes section. |
readOnly |
boolean | Configures the attribute to be read-only. Users will not be able to set the value of the attribute using Attribute's public API. |
writeOnce |
boolean or "initOnly" |
Configures the attribute to be write-once. Users will only be able to set the value of the attribute using
Attribute's If set to "initOnly", the attribute can only be set during initialization. In the case of Base, this means that the attribute can only be set through the constructor. Code within your class can update the value of readOnly or writeOnce attributes by using the private |
broadcast |
int | By default attribute change events are not broadcast to the YUI instance or global YUI object. The broadcast property can be used to set specific attribute change events to be broadcast to either the YUI instance or the global YUI object. See CustomEvent's broadcast property for valid values. |
lazyAdd |
boolean |
Whether or not to delay initialization of the attribute until the first call to get/set it.
This flag can be used to over-ride lazy initialization on a per attribute basis, when adding multiple attributes through
the When extending Base, all attributes are added lazily, so this flag can be used to over-ride lazyAdd behavior for specific attributes. The only reason you should need to disable |
cloneDefaultValue |
"shallow", "deep", true, false |
This configuration value is not actually supported by Attribute natively, but is available when working with Base, and defining attribute configurations using Base's static ATTRS property.
This property controls how the statically defined default |
Configuring Attributes
The above attribute properties are set using an object with property name/value pairs, which is passed to either addAttrs
or addAttr
as the
configuration argument. For example, expanding on the code snippet above:
... var attributeConfig = { attrA : { // Configuration for attribute "attrA" value: 5, setter: function(val) { return Math.min(val, 10); }, validator: function(val) { return Y.Lang.isNumber(val); } }, attrB : { // Configuration for attribute "attrB" } }; this.addAttrs(attributeConfig, userValues); ...
Or, if using addAttr
:
this.addAttr("attrA", { // Configuration for attribute "attrA" value: 5, setter: function(val) { return Math.min(val, 10); }, validator: function(val) { return Y.Lang.isNumber(val); } });
Attribute Change Events
The availability of attribute change events are one of the key benefits of using
attributes to store state for your objects, instead of regular object properties.
Attribute change events are fired whenever set
is invoked for an
attribute, allowing you to execute code in response to a change in the attribute's
value.
Listening for Change Events
Attribute change events are Custom Events, having the type: "[attributeName]Change", where [attributeName] is the name of the attribute which you're monitoring for changes.
For example, if you were interested in listening for changes to an attribute named "enabled", you would subscribe to events of type "enabledChange".
o.on("enabledChange", function(event) { // Do something just before "enabled" is about to be set });
NOTE: Context and additional arguments for the listener function can either be
defined using YUI's bind
method, or by passing in the context and
additional arguments to the on
method.
Attribute change event listeners can be registered using either the on
(as shown above) or after
Attribute methods.
On vs. After
On
Listeners registered using the on
method, are notified before the stored state of the attribute has been updated.
Functions registered as "on" listeners receive an Event
object as the first argument (actually an
instance of EventFacade
) which contains information
about the attribute being modified.
Since these listeners are invoked before any state change has occurred, they have the ability to
prevent the change in state from occurring, by invoking event.preventDefault()
on
the event object passed to them, or to modify the value being set, by modifying the event.newVal
property.
o.on("enabledChange", function(event) { // event.prevVal will contain the current attribute value var val = event.prevVal; if (val !== someCondition) { // Prevent "enabled" from being changed event.preventDefault(); } });
After
Listeners registered using the after
method, are notified after
the stored state of the attribute has been updated. As with "on" listeners, the subscribed function
receives an Event
object as the first parameter.
Based on the definition above, "after" listeners are not invoked if state change is prevented,
for example, due to one of the "on" listeners calling preventDefault
on the event object.
o.after("enabledChange", function(event) { // event.newVal will contain the currently set value var val = event.newVal; // Calling preventDefault() in an "after" listener has no impact event.preventDefault(); });
The Event Object
The event facade passed to attribute change event listeners, has a number of attributes which provide information about the attribute being modified, as well methods used to manage event propagation. These are described below:
- newVal
- The value which the attribute will be set to (in the case of "on" listeners), or has been set to (in the case of "after" listeners)
- prevVal
- The value which the attribute is currently set to (in the case of "on" listeners), or was previously set to (in the case of "after" listeners)
- attrName
- The name of the attribute which is being set
- subAttrName
Attribute also allows you to set individual properties of attributes having values which are objects through the
set
method (e.g.o.set("X.a.b", 5)
, discussed below). This event property will contain the complete dot notation path for the object property which was changed.For example, during
o.set("X.a.b", 5);
,event.subAttrName
will be"X.a.b"
, the path of the property which was modified, andevent.attrName
will be"X"
, the attribute name.- preventDefault()
- This method can be called in an "on" listener function to prevent the attribute's value from being updated (the default behavior). Calling this method in an "after" listener has no impact, since the default behavior has already been invoked.
- stopImmediatePropagation()
- This method can be called in "on" or "after" listener functions, and will prevent the rest of the listener stack from being notified, but will not prevent the attribute's value from being updated (viz. will not prevent the default behavior).
Attribute Set Flow Diagram
The diagram below shows the order in which attribute setters, validators and change event subscribers are invoked during the set operation:
NOTE: Any decision blocks for which an exit path is not explicitly shown will effectively exit the set operation, without storing the new value. These paths are not explicitly shown, in order to avoid clutter.
Getting/Setting Sub Attribute Values
If you have attribute values which are objects (as opposed to primitive values, such as numbers or booleans), the set
method will let
you set properties of the object directly, using a dot notation syntax. For example, if you have an attribute, "strings" with the following value:
o.set("strings", { ui : { accept_label : "OK", decline_label : "Cancel", }, errors : { e1000 : "Not Supported", e1001 : "Network Error" } });
You can set individual properties on the "strings" attribute value object, without having to get and then set the whole string's attribute value. This is done by using the dot notation to reference properties within the attribute's value:
// Set existing properties o.set("strings.ui.accept_label", "Yes"); o.set("strings.ui.decline_label", "No"); // Add a new property o.set("strings.errors.e2000", "New Error"); // Cannot set new intermediate properties: // "strings.messages" does not exist so can't set // "strings.messages.intro" o.set("strings.messages.intro", "Welcome");
Setting sub attribute values, will fire an attribute change event for the
main attribute ("stringsChange"
in the above example), however the event object passed
to the listeners with have a "subAttrName" property set to reflect the full path to the
attribute set (e.g. event.subAttrName
will be "strings.ui.accept_label"
for the set call on line 2 in the code snippet above).
You can also retrieve sub attribute values using the same dot notation syntax
// Get the string for the accept label var lbl = o.get("strings.ui.accept_label");
Getters, Setters, Validators and Sub Attributes
Getter, setter and validator attribute configuration functions are only defined for the top level
attribute ("strings"
in this case) and will be invoked when getting/setting sub attribute values.
What this means is that getters and setters should always return the massaged value for the top level
attribute (e.g. "strings"
), and not the sub attribute value being set (e.g. "strings.ui.accept_label"
).
The sub attribute being set is passed in as the second argument to the getter/setter/validator, so that it
can fork for sub attribute handling if required.
For example:
this.addAttr("strings", { getter : function(val, fullName) { // 'fullName' is "strings.errors.e4500" // 'val' is the whole strings hash: { ui : {...}, errors : {...}}. // 'path' is ["strings", "errors", "e4500"] var path = fullName.split("."); if (path.length > 1) { // Someone's asking for a sub-attribute value // Maybe we want to do some special normalization just for this use case. // For example, return a default error message instead of undefined. path.shift(); if (path[0] == "errors") { var leafValue = Y.Object.getValue(val, path); if (leafValue === undefined) { Y.Object.setValue(val, path, "Unknown Error"); } } } // In either case (sub attribute or not) val is always the full hash for the 'strings' attribute. return val; } });