Skip to content
IdahoEv edited this page Apr 25, 2012 · 5 revisions
  1. Behavior examples

A simple example, using some prepackaged behaviors:

        <script src="/js/jquery-1.4.js type="text/javascript"></script>
        <script src="/js/ns.min.js" type="text/javascript"></script>

        <script type="javascript">

 
        Ninja.orders(function(Ninja){  // boilerplate
          Ninja.behavior({
            "form.login_form": Ninja.submitsAsAjax,
            ".alert_notice": Ninja.decays({ lifetime: 5000 })
          })
        })
        </script>

This converts forms with class ‘login_form’ to AJAX equivalents, and makes all elements with class ‘alert_notice’ disappear after five seconds. All NinjaScript predefined behaviors have sensible defaults. If you don’t pass the options object to decays(), it will decay after 10 seconds instead of 5.

A more complex example, showing how you can define your own behaviors:

      <script src="/js/jquery-1.5.js type="text/javascript"></script>
      <script src="/js/ninjascript.js" type="text/javascript"></script>

      <script type="javascript">

      Ninja.orders(function(Ninja){  // boilerplate
        Ninja.behavior({
          "#mail form.new_mail": Ninja.ajax_submission,
          "#message_list .item": {
            transform: function(elem) {
              $(elem).delay(5000).slideUp(600, function(){$(elem).remove()})
            },
            click: function(event) {
              $(elem).remove()
            }
          },
          ".has_tooltip": {
            mouseover: function(event){
              myCreateMouseoverTip(elem)
            }
          }
        })
      })
      </script>

That behavior block sets up three behaviors:

  1. It converts a normal form (could be a POST, GET, whatever) into an AJAX submission. By default, we’ll put a “busy” overlay over the form until we get a response, and add any error messages to a list of error messages. This behavior is packaged as Ninja.submitsAsAjax
  2. It adds a decay behavior to messages, using jQuery effects.
  3. It applies a tooltip mouseover effect to elements with a “tooltip” class. We elide the details of what that effect is for the purposes of example.

Notice that behaviors are defined in three different, intermixable styles:

  1. Prepackaged, in the form of a method on the Ninja object (available everywhere as Ninja)
  2. With a “transform, events, helpers” syntax, which breaks out everything a behavior can do, completly explicitly.
  3. With an abbreviated events form, with the assumption that all we want to do is define a series of event handlers (and possibly a transformer)

Shorthand form for events

For simplicity of syntax, NinjaScript allows you to omit the ‘events’ wrapper when defining events, though in complex behaviors including multiple event handlers and a transform we encourage you to include it for clarity. This code:

      Ninja.orders(function(Ninja){  // boilerplate
        Ninja.behavior({
          '.some_class': { events: {
            click: function(event){ ... do something }
          }}
        })
      })

May be rewritten more briefly as:

      Ninja.orders(function(Ninja){  // boilerplate
        Ninja.behavior({
          '.some_class': { click: function(event){ ... do something } }
        })
      })
  1. Response Handlers

NS also allows you to specify JSON response handlers, allowing you to avoid attaching onSuccess() code directly to your AJAX submitters. This is convenient because it lets you DRY out your AJAX code: you can trigger the same response handler (or an overlapping set of response handlers!) from many different ajax actions.

  Ninja.behavior({ 
    "#recommendation_form, #delete_recommendation_button": Ninja.submitsAsAjax({ actions: true })
  })
  Ninja.respondToJson({

    // Successful update and successful create of a recommendation object.
    recommendation : function(recommendation){
      // Update the recommendation on-screen, if there is one.
      $("#" + recommendation.dom_id + " .body").html(recommendation.body);

      // Remove the dialog and form, if there is on.
      $("#recommendations form").remove();
      $(".recommendation_form_dialog").slideUp(600, function(){ $(this).remove() });
    },

   // removal of a recommendation object
    recommendation_removed : function(dummy){
      $("body.providers.profile #recommended").text("");
    }

  });

The behavior block just sets a few elements to submit AJAX requests rather than plain requests. It works on either links or forms. The {actions: true} sets HTTP-ACCEPT to application/json rather than application/javascript, which is the default.

The responder block creates two response handlers. If the browser receives any JSON doc in response to an AJAX request, it will get checked for keys ‘recommendation’ and ‘recommendation_removed’. If either matches, the appropriate response handler will get called. This is entirely decoupled from the AJAX submitters, so you can trigger these actions from different submitters, and/or different behaviors on the server. In this example (which is from an LRD project), we will pass back a ‘recommendation’ entry in response to either a new recommendation or an edited recommendation.

Clone this wiki locally