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.
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.18.1/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.
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.
Once augmented with Attribute, your class can either use the addAttrs
method to setup attributes en masse, 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!");
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, the name of the attribute as the second argument and the third argument passed to the The setter may return the constant 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 ( The third argument is optional and it should have been an object. It may be used to give the reason or origin of the change. This allows the setter to manipulate the value in special ways when it comes from certain sources or to decide whether to accept it or not. |
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. The third argument is optional and it should have been an object. It may be used to give the reason or origin of the change. This allows the validator to accept a value when it comes from certain sources while rejecting it in general. |
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 |
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 adds set
and get
methods to the object it augments.
myObject.set("attrA", 6); Y.log(myObject.get("attrA")); // should log 6
Several attributes can be set or read at once via the setAttrs
and getAttrs
methods.
myObject.setAttrs({ age: 6, name: "John" }); Y.log(Y.Lang.sub("{name} is {age} years old", myObject.getAttrs()));
Calling getAttrs
without any arguments will return all the configured attributes.
Passing an array of attribute names will return only those. Passing true
will return only those modified from its initially configured value.
A protected _set
method allows changing the value of attributes configured as readOnly
or past the first write in those configured as writeOnce
, to allow the
object to still enforce those rules in the public API while allowing the
object to change the values internally.
An extra argument can be provided to set
and setAttrs
indicating the
reason or origin of the change. This argument must be an object and it will
be passed to the setter
and/or validator
methods, if any, and it will
be merged into the event facade of the attribute change events.
myObject.set("attrA", inputNode.get("value"), {src:"UI"}); myObject.setAttrs({ attrA: null, attrB: "" },{src:"internal"});
This may allow an object to set an attribute to a value otherwise forbidden
in the public API, to have the setter
manipulate it in a special way or
an attribute change event to respond in a particular manner. For example, as shown
in the sample code above,
a setter
may accept and parse a numeric string when the the source of the
change is the UI while it would reject it otherwise.
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.
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.
Attribute change event listeners may respond differently according to the
source or reason of the change as specified in the third argument to set
.
This argument will be merged into the event facade and can be checked by the
event listener.
myObject.after("nameChange", function (event) { if (event.src !== "UI") { inputNode.set("value", event.newVal); } });
The code above listens to changes in the name
attribute and, if it comes
from anywhere but the UI, it sets the input box to the new value.
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.
The value passed to the "on" event listener has not yet been checked via the validator
or
normalized by the setter
method. Since the change may later be rejected or prevented
by further event listeners attached later, an "on" event listener should not
produce any secondary effects.
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(); } });
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.
They are not invoked either if the validator
or setter
methods
rejected the value and they will receive the value already modified by the setter
thus
it is safe to produce any secondary effects based on the changed value.
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 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:
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, and event.attrName
will be "X"
, the attribute name.
set
or setAttrs
call.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.
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");
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; } });