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) {
      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 – this way, the innards of defining behaviors remain somewhat encapsulated. The helper has 3 methods:
ninja.does(behaviorDefinition)
This defines a behavior, pretty much exactly like an ad hoc definition.
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)
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()
Clone this wiki locally