YUI 3.x Home -

YUI Library Examples: Attribute: Attribute Based Speed Dating

Attribute: Attribute Based Speed Dating

This example builds on the "Basic Configuration" example, showing how you can use attribute to model objects in your application.

As with the basic example, it is geared towards users who want to create their own classes from scratch and add attribute support. In most cases you should consider extending the Base class when you need attribute support, instead of augmenting Attribute directly. Base does the work described in this example for you, in addition to making it easier for users to extend you class.

Speed Dating With Attributes

Setting Up a SpeedDater Class

In this example, we'll create a custom SpeedDater class, and show how you can use attributes to manage the state for a Speed Dater. In the "Attribute Event Based Speed Dating" example we'll modify this example to leverage attribute change events.

Creating A YUI Instance

As with the other attribute examples, we'll setup our own instance of the YUI object and request the modules we require using the code pattern shown below:

  1. <script type="text/javascript">
  2.  
  3. // Create our local YUI instance, to avoid
  4. // modifying the global YUI object
  5.  
  6. YUI({...}).use("attribute", "node", ... function(Y) {
  7.  
  8. // Example code is written inside this function,
  9. // which gets passed our own YUI instance, Y, populated
  10. // with the modules we asked for (e.g. Y.Attribute, Y.Node etc.)
  11.  
  12. });
  13. </script>
<script type="text/javascript">
 
    // Create our local YUI instance, to avoid
    // modifying the global YUI object
 
    YUI({...}).use("attribute", "node", ... function(Y) {
 
        // Example code is written inside this function,
        // which gets passed our own YUI instance, Y, populated
        // with the modules we asked for (e.g. Y.Attribute, Y.Node etc.)
 
    });
</script>

Defining The SpeedDater Class

The first step in the example is to create the constructor function for our new class, to which we want to add attribute support. In our example, this class is called SpeedDater. We then augment SpeedDater with Y.Attribute, so that it receives all of Attribute's methods, in addition to any it may defined itself:

  1. // Setup custom class which we want to add attribute support to
  2. function SpeedDater(cfg) {
  3. ...
  4. }
  5.  
  6. // Augment custom class with Attribute
  7. Y.augment(SpeedDater, Y.Attribute);
// Setup custom class which we want to add attribute support to
function SpeedDater(cfg) {
    ...
}
 
// Augment custom class with Attribute
Y.augment(SpeedDater, Y.Attribute);

Adding Attributes

We can now set up any attributes we need for SpeedDater using Attribute's addAttrs() method. For this example we add 3 attributes - name, personality, and available. We provide an default initial value for personality and available, but don't have anything for name. As mentioned in the basic example, the same object literal we use to provide the initial value for the attribute can also be used to configure attribute properties such as readOnly or writeOnce, and to define getter, setter and validator methods for the attribute. For name, we configure it to be writeOnce, meaning that it's value can be set once by the user, but not modified after that single set.

The default set of attributes which SpeedDater will support is passed to addAttrs to set up the attributes for each instance during construction.

As mentioned previously, if you expect your class to be extended, Base provides a more convenient way for you to define the same attribute configuration statically for your class, so that it can be modified by extended classes. Base will take care of isolating the static configuration, so that it isn't modified across instances.

The complete definition for SpeedDater is shown below:

  1. // Setup custom class which we want to
  2. // add managed attribute support to
  3.  
  4. function SpeedDater(cfg) {
  5.  
  6. // When constructed, setup the initial attributes for the
  7. // instance, by calling the addAttrs method.
  8.  
  9. var attrs = {
  10. // Add 3 attributes: name, personality, available
  11. name : {
  12. writeOnce:true
  13. },
  14.  
  15. personality : {
  16. value:50
  17. },
  18.  
  19. available : {
  20. value:true
  21. }
  22. };
  23.  
  24. this.addAttrs(attrs, cfg);
  25. }
  26.  
  27. SpeedDater.prototype.applyNameTag = function(where) {
  28. // Method used to render the visual representation of a
  29. // SpeedDater object's state (in this case as a name tag)
  30. };
  31.  
  32. SpeedDater.prototype.updateNameTag = function() {
  33. // Method used to update the rendered state of SpeedDater in the DOM.
  34. }
  35.  
  36. // Template to use form the markup
  37. SpeedDater.NAMETAG = "<div class="sd-nametag"><div class="sd-hd">Hello!</div>... </div>";
  38.  
  39. // Augment custom class with Attribute
  40. Y.augment(SpeedDater, Y.Attribute);
// Setup custom class which we want to 
// add managed attribute support to
 
function SpeedDater(cfg) {
 
    // When constructed, setup the initial attributes for the
    // instance, by calling the addAttrs method.
 
    var attrs = {
        // Add 3 attributes: name, personality, available
        name : {
            writeOnce:true
        },
 
        personality : {
            value:50
        },
 
        available : {
            value:true
        }
    };
 
    this.addAttrs(attrs, cfg);
}
 
SpeedDater.prototype.applyNameTag = function(where) {
    // Method used to render the visual representation of a 
    // SpeedDater object's state (in this case as a name tag)
};
 
SpeedDater.prototype.updateNameTag = function() {
    // Method used to update the rendered state of SpeedDater in the DOM.
}
 
// Template to use form the markup    
SpeedDater.NAMETAG = "<div class="sd-nametag"><div class="sd-hd">Hello!</div>... </div>";
 
// Augment custom class with Attribute
Y.augment(SpeedDater, Y.Attribute);

The addAttrs() method, in addition to the default attribute configuration, also accepts an object literal (associative array) of name/value pairs which can be used to over-ride the default initial values of the attributes. This is useful for classes which wish to allow the user the set the value of attributes as part of object construction, as shown by the use of the cfg argument above.

Using Attributes

Now that we have SpeedDater defined with the set of attributes it supports, we can create multiple instances of SpeedDater defining the initial attribute state for each instance through the constructor. We can also update the instance's attribute state after construction, using the get and set methods defined by Attribute.

We create a first instance, john, setting up the intial state using Attribute's constructor configuration object support:

  1. // Set both name and personality during construction
  2. john = new SpeedDater({
  3. name: "John",
  4. personality: 76.43
  5. });
// Set both name and personality during construction 
john = new SpeedDater({
    name: "John",
    personality: 76.43
});

For the second instance that we create, jane, we set the value of the personality attribute, after construction:

  1. // Set name during construction
  2. jane = new SpeedDater({
  3. name: "Jane"
  4. });
  5.  
  6. // Set personality after construction. The initial value for personality
  7. // in this case, will be the value defined when the attribute was added
  8. // using addAttrs (above)
  9. jane.set("personality", 82);
// Set name during construction
jane = new SpeedDater({
    name: "Jane"
});
 
// Set personality after construction. The initial value for personality 
// in this case, will be the value defined when the attribute was added 
// using addAttrs (above)
jane.set("personality", 82);

We render the current attribute state of each instance to the DOM, using the applyNameTag() method defined on SpeedDater's prototype:

  1. // Render the sticker with john's state information to the DOM
  2. john.applyNameTag("#john .shirt");
  3.  
  4. // Render the sticker with jane's state information to the DOM
  5. jane.applySicker("#jane .shirt");
// Render the sticker with john's state information to the DOM
john.applyNameTag("#john .shirt");
 
// Render the sticker with jane's state information to the DOM
jane.applySicker("#jane .shirt");

Although not directly related to working with Attributes, it's worth taking a look at the applyNameTag() and updateNameTag() implementations, since they establish a commonly used pattern.

The applyNameTag() method handles rendering the initial visual representation for a speed dater object's state (in this case a name tag). It uses tokens in an HTML "template" string, which it replaces with the values of attributes using the substitute() utility method:

  1. // A template for the markup representing the SpeedDater object..
  2. SpeedDater.NAMETAG = '<div class="sd-nametag"> \
  3. <div class="sd-hd">Hello!</div> \
  4. <div class="sd-bd">I\'m <span class="sd-name">{name}</span> \
  5. and my PersonalityQuotientIndex is \
  6. <span class="sd-personality">{personality}</span> \
  7. </div> \
  8. <div class="sd-ft sd-availability">{available}</div> \
  9. </div>';
// A template for the markup representing the SpeedDater object..
SpeedDater.NAMETAG = '<div class="sd-nametag"> \
                        <div class="sd-hd">Hello!</div> \
                        <div class="sd-bd">I\'m <span class="sd-name">{name}</span> \ 
                        and my PersonalityQuotientIndex is \ 
                        <span class="sd-personality">{personality}</span> \
                        </div> \
                        <div class="sd-ft sd-availability">{available}</div> \
                     </div>';
  1. // A rendering method, used to create the initial markup for the SpeedDater.
  2. SpeedDater.prototype.applyNameTag = function(where) {
  3.  
  4. // This example uses an HTML template string containing placeholder
  5. // tokens (SpeedDater.NAMETAG above), and Y.substitute to replace the
  6. // tokens with the current attribute values.
  7.  
  8. var tokens = {
  9. // Get attribute values and map them to the tokens in the HTML template string
  10. name: this.get("name"),
  11. available: (this.get("available")) ? "I'm still looking " : "Sorry, I'm taken",
  12. personality: this.get("personality")
  13. };
  14.  
  15. // Create a new Node element, from the token substituted string...
  16. this.nameTag = Y.Node.create(Y.substitute(SpeedDater.NAMETAG, tokens));
  17.  
  18. // ... and append it to the DOM
  19. Y.one(where).appendChild(this.nameTag);
  20. };
// A rendering method, used to create the initial markup for the SpeedDater.
SpeedDater.prototype.applyNameTag = function(where) {
 
    // This example uses an HTML template string containing placeholder 
    // tokens (SpeedDater.NAMETAG above), and Y.substitute to replace the 
    // tokens with the current attribute values.  
 
    var tokens = {
        // Get attribute values and map them to the tokens in the HTML template string
        name: this.get("name"),
        available: (this.get("available")) ? "I'm still looking " : "Sorry, I'm taken",
        personality: this.get("personality")
    };
 
    // Create a new Node element, from the token substituted string... 
    this.nameTag = Y.Node.create(Y.substitute(SpeedDater.NAMETAG, tokens));
 
    // ... and append it to the DOM
    Y.one(where).appendChild(this.nameTag);
};

The updateNameTag() method handles updating this visual representation with the current state, when requested by the user

  1. // An update method, used to refresh the rendered content, after
  2. // an attribute value is changed.
  3. SpeedDater.prototype.updateNameTag = function() {
  4.  
  5. // Get current attribute values...
  6. var taken = (this.get("available")) ? "I'm still looking " : "Sorry, I'm taken";
  7. var name = this.get("name");
  8. var personality = this.get("personality");
  9.  
  10. // Find the corresponding element, and replace the innerHTML with the new value
  11. this.nameTag.query(".sd-name").set("innerHTML", name);
  12. this.nameTag.query(".sd-availability").set("innerHTML", taken);
  13.  
  14. var personalityEl = this.nameTag.query(".sd-personality");
  15. personalityEl.set("innerHTML", personality);
  16.  
  17. if (personality > 90) {
  18. personalityEl.addClass("sd-max");
  19. }
  20. }
// An update method, used to refresh the rendered content, after 
// an attribute value is changed.
SpeedDater.prototype.updateNameTag = function() {
 
    // Get current attribute values...
    var taken = (this.get("available")) ? "I'm still looking " : "Sorry, I'm taken";
    var name = this.get("name");
    var personality = this.get("personality");
 
    // Find the corresponding element, and replace the innerHTML with the new value
    this.nameTag.query(".sd-name").set("innerHTML", name);
    this.nameTag.query(".sd-availability").set("innerHTML", taken);
 
    var personalityEl = this.nameTag.query(".sd-personality"); 
    personalityEl.set("innerHTML", personality);
 
    if (personality > 90) {
        personalityEl.addClass("sd-max");
    }
}

Each instance's state can be now be updated using Attribute's set method, and the subsequent call to SpeedDater's updateNameTag() method will update the visual representation (the rendered DOM) of the object:

  1. Y.on("click", function() {
  2.  
  3. john.set("available", false);
  4. john.updateNameTag();
  5.  
  6. }, "#john .taken");
  7.  
  8. Y.on("click", function() {
  9.  
  10. jane.set("available", false);
  11. jane.updateNameTag();
  12.  
  13. }, "#jane .taken");
  14.  
  15. Y.on("click", function() {
  16.  
  17. jane.set("personality", 98);
  18. jane.updateNameTag();
  19.  
  20. }, "#jane .upgrade");
Y.on("click", function() {
 
    john.set("available", false);
    john.updateNameTag();
 
}, "#john .taken");
 
Y.on("click", function() {
 
    jane.set("available", false);
    jane.updateNameTag();
 
}, "#jane .taken");
 
Y.on("click", function() {
 
    jane.set("personality", 98);
    jane.updateNameTag();
 
}, "#jane .upgrade");

In the "Attribute Event Based Speed Dating" example, we'll see how we can use Attribute change events to eliminate the need for users to call updateNameTag() each time they set an attribute, and have the two instances communicate with one another.

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings