Behaviors

Overview

The Mootools community has introduced Behaviors, which QBO 3 will make extensive use of.

In short, behaviors standardizes the methodology QBO 2.0's qbo.js was using to bind javascript objects to HTML elements.  For example, in QBO 2.0, we might have:

<input type="text" name="PaidDate" class="qbo-date" data-options="{some options}"/>

The qbo.js would "wire" this to a javascript object that handles date fields along these lines:

$$('.qbo-date').each(function() ...);

Behaviors is a framework for automating such binding, with the following advantages:
  • multiple behaviors can be attached to 1 element,
  • initialization can be deferred until a user clicks on the element (e.g. don't create the menu until you need to)
  • onCleanup methods prompt developers to "clean up" memory
So with behaviors, we have instead:

<input type="text" name="PaidDate" data-behavior="Date" data-date-options={"some options"}>

and elsewhere, a Behavior filter like this:

Behavior.addGlobalFilter(function(element, api) {
  var something = new SomeObject(...);
  var myOption = api.get('someOption');

  var options = api.getAs({
    optionA: String,
    optionB: Number,
    optionC: String
  });
  alert(options.optionA);
  ... extra code ...
  api.onCleanup(function(){
    // remote events, extra DOM elements created, etc. to manage memory
  });
});

Applying Behaviors to Dynamic Content

If DOM content is created dynamically (either by an AJAX call or via javascript), one should apply behaviors with:

qbo3.behavior.apply(element);

For example, creating a new data control with javascript could be done with:

myDate = new Element('input', {
  'type': 'text',
  'name': 'myDate',
  'data-behavior': 'Date',
  'data-date-options': {some options here}
}).inject(someLocation);
qbo3.behavior.apply(myDate);