data driven behavior


<hr data-start-presentation="slide1" />

custom data attributes

  • HTML5
  • data-* attributes on DOM elements
  • store custom data private to the page or application
  • Can be set on nodeType 1:ELEMENT_NODE and 9:DOCUMENT_NODE
  • Example:

 <div class="person" data-year-of-birth="1952">The Hoff</div>

WHY PRIVATE attributes?!

W3C Code Example:

If a Web page wanted an element to represent a space ship, e.g. as part of a game, it would have to use the class attribute along with data-* attributes:

<div class="spaceship" data-ship-id="92432"
     data-weapons="laser 2" data-shields="50%"
     data-x="30" data-y="10" data-z="90">
 <button class="fire"
Notice how the hyphenated attribute name becomes camel-cased in the API.


interface DOMStringMap {
  getter DOMString (DOMString name);
  setter creator void (DOMString name, DOMString value);
  deleter void (DOMString name);

  • "data-" is removed (first five)
  • "-" is interpreted as separator and name is converted to camelCase
  • data-foo-bar="" becomes element.dataset.fooBar

jQuery data handling

  • Reads > caches > stores private data
  • Initially loads data from attributes with neat logic
  • Provides simple interface to dataset
<div data-foo-bar="Hello World"></div>
 // Obtain data
 var dataFnc = $(this).data.bind($(this));
 // Modify data
 dataFnc('fooBar', dataFnc('fooBar').split('').reverse().join(''));

jQuery data attribute conversion

if ( typeof data === "string" ) {
  try {
    data = data === "true" ? true :
    data === "false" ? false :
    data === "null" ? null :
    // Only convert to a number if it doesn't change the string    +data + "" === data ? +data :
    rbrace.test( data ) ? jQuery.parseJSON( data ) :  data;  } catch( e ) {}
    // Make sure we set the data so it isn't changed later elem, key, data );} else {
  data = undefined;

So what's data driven behavior?!

  • Develop API for use in HTML with data-* attributes
  • Build portable behavior based on your information data (HTML)
  • Create easy to use API that works without any script involvement (declarative style in HTML)
  • Establish core commons behavior library that can be re-used
  • Nice interface from back-end into front-end (configuration / initial settings)

CSS: "Here are my two cents!"

  • Attribute selectors [data-foo-bar*="test"]
  • Works nicely in conjunction with pseudo elements :before and :after using content: attr(data-foo-bar);
  • Great for icon fonts: data-icon="&#x03b;"

Some sample use cases


Data driven behavior

By Gion Kunz

Data driven behavior

  • 2,301