euge edited this page Sep 13, 2010 · 2 revisions

What’s a Behavior?

A behavior is simply the reaction of a DOM element to an event, such as the clicking of a link or the submission of a form.

Using inline Javascript to define behaviors on elements has fallen out of favor for more unobtrusive techniques. These techniques allow for greater flexibility, increased performance, and encourage the separation of behavior (Javascript) from the markup (HTML), leading to more DRY code and greater reusability.

However, as your application’s UI becomes richer and the number of pages increases, you will find that maintaining unobtrusive javascript becomes problematic. This is particularly evident in AJAX heavy applications that replace and update various sections of a page. Event delegation (more info in FAQ) mitigates this to a large extent, but can become a bottleneck itself as more behaviors are added. For example, an application with 30 behaviors requires that each one is processed in order to find the correct one to execute every time a link is clicked.

behaveJS solves these problem by allowing DOM elements to express how they should behave. Using the familiar “style” syntax, behaviors are defined on elements utilizing HTML5 compatible custom attributes.


Consider the call to the following behaveJS Rails helper and the output it generates.

# generates: <a href="/items/2" data-behaves="click:showDialog;mouseover:xyz;">Show</a>
link_to("Show", item_path(@item), :behaves => {:click => :showDialog, :mouseover => :xyz})

The link above uses two different behaviors and it is apparent that when clicked, the link “behaves” by executing the “showDialog” behavior and on the mouseover event, the make_big behavior will be executed.

Behaviors are then simply defined in your page’s javascript.

  showDialog : function(event)
    // your code here...
  xyz : function(event)
    // your code here...

behaveJS manages all behavior assignment and use event delegation completely on its own, requiring no effort from you. It also provides the ability to scope behaviors to specific controllers and actions, allowing for behaviors to be overridden in certain cases.

With behaveJS, not only are behaviors reusable, they are located in a single place and also enable event delegation to be very efficient. Only one event handler is ever used in your entire page for all click behaviors. Whenever an element is clicked, behaveJS knows exactly which behavior to run without the overhead of searching for it.