Classes are for designers. data-behavior is for JavaScript developers.

I have written a lot of JavaScript code like this

$(".product_pictures .actions .delete").on "click", ->

The problem with above code is that class names in the html markup was meant for web design. By using css class for functional work, I have made both the design team and the front end development team perpetually terrified of change.

Class is meant for CSS

If designer wants to change markup from

<div class='first actions'>xxx<div>


<div class='first actions-items'>xxx<div>

they are not too sure what JavaScript code might break. So they work around it.

Same goes for JavaScript developers. They do not want to unintentionally remove a class element otherwise the web design might get messed up.

There has to be a better way which clearly separates the design elements from functional elements.

data-behavior to rescue

“Nick Quaranto” of 37Signals presented “Code spelunking in the All New Basecamp” ( video blog ) . In his presentation he mentioned about data-behavior .

data-behavior usage can be best understood by an example.

# no data-behavior
$(".product_pictures .actions .delete").on("click", function(){});
# code with data-behavior
$('[data-behavior~=delete-product-picture]').on('click', function(){});

# Another style with same effect
$(document).on('click',"[data-behavior~=delete-product-picture]",  function(){ });

The html markup will change from

<%= link_to '#', class: 'delete', "data-action-id" => do %>


<%= link_to '#', class: 'delete', "data-action-id" =>, 'data-behavior' => 'delete-product-picture' do %>

Above code would produce html code something like this

<a class="delete" data-action-id="" data-behavior="delete-product-picture" href="#">

Now in the above case the designer can change the css class all he wants and it will have no impact on JavaScript functionality.

More usage of data-behavior

Based on this data-behavior approach I changed some part of nimbleShop to use data-behavior. Here is the commit.

Personally I am surprised at people using old style of development. data-behavior is a very simple and effective tool to combat the problem of having clear separation between designer elements and JavaScription functional work.

No spam. Delivered around once a month.