Skip to content
Judson edited this page Jul 7, 2011 · 1 revision

Several Ninjascript behaviors trigger an AJAX request. By default we make a jQuery-style “script” request: we send an Accept header that looks for text/javascript and we eval the result. There are many issues with this approach, too numerous to go into here. It’s tempting to say “you’re using eval” and leave it at that. If nothing else, the resulting errors are really obnoxious to debug. There are also severe restrictions on what you can do from within an eval’d Javascript snippet.

Ninjascript makes it easy to handle JSON responses, and all the packaged behaviors give the option of passing JSON handlers in to describe what you want to do with the JSON response.

Handlers are simply Javascript objects, whose members are either functions, or are nested handlers. Like this:

{ name: function(name){ alert(name) },
  wallet: {
    drivers_license: function(dl){ alert(dl.number) }
  }}

When JSON comes back as an XHR response, we compare the JSON to the handler object and see what matches up – any field in the handler object that matches a field in the JSON will get passed the value of the field. In other words, if we received:

{ "name": "Judson", 
"wallet": { "dan_card": {"number": "12345", "level": "AOW"}, 
"drivers_license": { "number": "4567", "state": "CA" }}}

then the above handler would alert “Judson” and “4567” – in no guaranteed order.

The intention is that it be possible to build well-decoupled front and back end applications – leave the handling of the data to your view layer, and the structure of the data to the presentation layer.