Rule

A Rule connects a behavior to a CSS selector.

Rules are live. The jsb rule engine will constantly scan the document looking for matching elements. The benefits of this are:

The jsb rule engine is pretty fast and will typically attach behaviors within milliseconds of an element being inserted into the document. If you cannot wait milliseconds, then you can always attach the behavior immediately using the attach() method of the behavior or the refresh() method of the Rule.

Creating Rules

Use the new operator to create a Rule:

new jsb.Rule("div.example", mybehavior);

The first argument is a CSS selector.

The second argument can be one of three things:

Here's an example that defines a one-off behavior described by an object literal:

new jsb.Rule("div.example", {
  onclick: function() {
    alert("You clicked me!");
  }
});

External Behaviors

You can reference an external resource by creating a Rule with the second argument pointing to the resource:

new jsb.Rule("div.example", "/assets/js/widgets.js#widget");

The resource is described in two parts, the first is a path to the JavaScript file that contains the behavior. The second part describes a reference to the behavior object. In the example above, widgets.js should define a global variable called "widget".

Here's another example. In this case, the file ui.js defines a number of behaviors all attached to a global object called "ui":

new jsb.Rule("input.spinner", "ui.js#ui.spinner");

External behaviors are not loaded until a matching element is found by the jsb rule engine.

Properties and Methods

Rules are merely connector objects. They only have one method: refresh(). You can refresh a Rule at any time. When you call refresh(), the entire document is scanned for elements that match the Rule. New matching elements are immediately attached.

var spinners = new jsb.Rule("input.spinner", ui.spinner);

spinners.refresh();

You do not need to call the refresh() method. The jsb rule engine will maintain attachments for you.