28 Feb 2010

Dojo AttributeMap

Posted by gavin

When using Dojo templating, most guides on the web suggest using ${variable} in your template, where variable is the name of one of your widget’s attributes. When writing my first custom widget, I couldn’t get this to work; no matter what I tried the templating engine would not replace ${} blocks.

Frantically searching for a solution, I found numerous references to using an “attribute map” instead of ${}, but the documentation was pretty poor.

Basically, you can add an attribute map by declaring an attribute in your widget called attributeMap. You then perform a mapping between attribute name in your widget and node in your template.

dojo.declare(
    'customWidgets.MyWidget',
    [dijit._Widget, dijit._Templated],
    {
        variable : 'myVar',

        attributeMap : {
            // key is attribute name, value is node identifier
            variable : 'myNode',
        },

        templatePath :
            new dojo.moduleUrl('customWidgets', 'MyWidget.html')
    }
);

This seems pretty straightforward. Except… well:

  1. What is myNode
  2. What part of myNode does it bind to?

In your template, you need to declare a dojoAttachPoint, which will become your node. This is pretty straightforward:

<div dojoAttachPoint="myNode"></div>

For point 2, what this will actually do, is create an HTML attribute called variable in your <div>, i.e.

<div variable="myVar"></div>

This may or may not be useful. You can invoke this behaviour more explicitly

        attributeMap : {
            variable : {
                node : 'myNode',
                type : 'attribute'
            }
        },

If you want the div‘s contents to take your value, you can set type to innerHTML. The bit of info that’s useful to know, however, is that you can add a third property called attribute:

        attributeMap : {
            variable : {
                node : 'myNode',
                type : 'attribute',
                attribute : 'alt'
            }
        },

In this example, variable will be mapped to the alt property of myNode. Very useful if you want to set a src on 2 separate images, for example.

VN:F [1.9.6_1107]
Rating: 9.0/10 (2 votes cast)
Dojo AttributeMap, 9.0 out of 10 based on 2 ratings
  • Print
  • Add to favorites
  • Facebook
  • StumbleUpon
  • del.icio.us
  • FriendFeed
  • Twitter
  • Digg

Leave a Reply

Message:

  • Browse

    or
  • Latest Content

  • Gallery

    Chopping almonds for the pud 2010_0110Wales0010 200910_Wales0026 2010_0102XmasAndNewYear0092
  • Tags

  • RSS<img src="http://www.gavinwillingham.com/wp-content/plugins/twitter-widget-pro/twitter_logo_s.png" height="21" width="92" alt="twitter logo" />

  • Comments