Skip to content
Judson edited this page Jul 7, 2011 · 5 revisions

Once you’ve defined an ad hoc behavior, it’s often nice to be able to package it up, parameterize it, and reuse it in your own projects, or publish them for general use. So long as Ninjascript has already been loaded, behavior packages can appear later in the document and are available immediately thereafter. We’re also very open to including generally useful behaviors in future releases of Ninjascript.

The overview of packaging a behavior:

Ninja.packageBehaviors(function(ninja){
  return {
    myBehavior: function(configs) {
      configs = Ninja.tools.ensureDefaults(configs, {some: defaults})
      return new ninja.does({
        ... regular ad hoc def here ...
      })},
    anotherBehavior: function(configs) {
      ...
      }
    }}})
Ninja.packageBehaviors(function(ninja))
Receives a function which takes as an argument a behavior definition helper. Returns an object with behavior definition methods, which will take a configuration object as an argument and return a Behavior. The helper has 3 constructors:
new ninja.does(behaviorDefinition)
This defines a behavior, pretty much exactly like an ad hoc definition.
new ninja.selects(selectionDefinition)
Defines a selecting behavior: a bundle of regular behaviors that get applied based on whether a particular CSS selector matches the element passed into transform(elem)
new ninja.chooses(choiceDefinition)
Defines a “metabehavior”: essentially a selecting behavior where the choice of application depends on the result of a choose() method on the behavior. The easy example here is the becomesAjax()
Ninja.tools.ensureDefaults(configs, defaults)
returns what amounts to a reverse merge of the defaults and the configs passed in. Very handy for making sure all the values get set.