Fork me on GitHub

Sammy

Documentation

API

Sammy ( )

Sammy (also aliased as $.sammy) is not only the namespace for a number of prototypes, its also a top level method that allows for easy creation/management of Sammy.Application instances. There are a number of different forms for Sammy() but each returns an instance of Sammy.Application. When a new instance is created using Sammy it is added to an Object called Sammy.apps. This provides for an easy way to get at existing Sammy applications. Only one instance is allowed per element_selector so when calling Sammy('selector') multiple times, the first time will create the application and the following times will extend the application already added to that selector.

Example

Sammy.addLogger ( logger )

Add to the global logger pool. Takes a function that accepts an unknown number of arguments and should print them or send them somewhere The first argument is always a timestamp.

Sammy.log ( )

Sends a log message to each logger listed in the global loggers pool. Can take any number of arguments. Also prefixes the arguments with a timestamp.

Sammy.Object ( obj )

Sammy.Object is the base for all other Sammy classes. It provides some useful functionality, including cloning, iterating, etc.

Methods


has ( key )

Checks if the object has a value at key and that the value is not empty

join ( )

convenience method to join as many arguments as you want by the first argument - useful for making paths

keys ( attributes_only )

Returns an array of keys for this object. If attributes_only is true will not return keys that map to a function()

log ( )

Shortcut to Sammy.log

toHTML ( )

Renders a simple HTML version of this Objects attributes. Does not render functions. For example. Given this Sammy.Object:

toHash ( )

Returns a copy of the object with Functions removed.

toString ( include_functions )

Returns a string representation of this object. if include_functions is true, it will also toString() the methods of this object. By default only prints the attributes.

uuid ( )

Generates a unique identifing string. Used for application namespaceing.

Sammy.HashLocationProxy ( app, run_interval_every )

The HashLocationProxy is the default location proxy for all Sammy applications. A location proxy is a prototype that conforms to a simple interface. The purpose of a location proxy is to notify the Sammy.Application its bound to when the location or ‘external state’ changes. The HashLocationProxy considers the state to be changed when the ‘hash’ (window.location.hash / ’#’) changes. It does this in two different ways depending on what browser you are using. The newest browsers (IE, Safari > 4, FF >= 3.6) support a ‘onhashchange’ DOM event, thats fired whenever the location.hash changes. In this situation the HashLocationProxy just binds to this event and delegates it to the application. In the case of older browsers a poller is set up to track changes to the hash. Unlike Sammy 0.3 or earlier, the HashLocationProxy allows the poller to be a global object, eliminating the need for multiple pollers even when thier are multiple apps on the page.

Methods


bind ( )

bind the proxy events to the current app.

getLocation ( )

get the current location from the hash.

setLocation ( new_location )

set the current location to new_location

unbind ( )

unbind the proxy events from the current app

Sammy.DataLocationProxy ( app, data_name )

The DataLocationProxy is an optional location proxy prototype. As opposed to the HashLocationProxy it gets its location from a jQuery.data attribute tied to the application’s element. You can set the name of the attribute by passing a string as the second argument to the constructor. The default attribute name is ‘sammy-location’. To read more about location proxies, check out the documentation for Sammy.HashLocationProxy

Sammy.Application ( app_function )

Sammy.Application is the Base prototype for defining ‘applications’. An ‘application’ is a collection of ‘routes’ and bound events that is attached to an element when run() is called. The only argument an ‘app_function’ is evaluated within the context of the application.

Attributes


APP_EVENTS = ['run','unload','lookup-route','run-route','route-found','event-context-before','event-context-after','changed','error','check-form-submission','redirect']

An array of the default events triggered by the application during its lifecycle

ROUTE_VERBS = ['get','post','put','delete']

the four route verbs

any = _routeWrapper('any')

Alias for route(‘any’, …)

debug = false

When set to true, logs all of the default events using log()

del = _routeWrapper('delete')

Alias for route(‘delete’, …)

element_selector = 'body'

Defines what element the application is bound to. Provide a selector (parseable by jQuery()) and this will be used by $element()

get = _routeWrapper('get')

Alias for route(‘get’, …)

location_proxy = null

The location proxy for the current app. By default this is set to a new Sammy.HashLocationProxy on initialization. However, you can set the location_proxy inside you’re app function to give youre app a custom location mechanism

post = _routeWrapper('post')

Alias for route(‘post’, …)

put = _routeWrapper('put')

Alias for route(‘put’, …)

raise_errors = false

When set to true, and the error() handler is not overriden, will actually raise JS errors in routes (500) and when routes can’t be found (404)

run_interval_every = 50

The time in milliseconds that the URL is queried for changes

template_engine = null

The default template engine to use when using partial() in an EventContext. template_engine can either be a string that corresponds to the name of a method/helper on EventContext or it can be a function that takes two arguments, the content of the unrendered partial and an optional JS object that contains interpolation data. Template engine is only called/refered to if the extension of the partial is null or unknown. See partial() for more information

Methods


$element ( )

returns a jQuery object of the Applications bound element.

after ( callback )

A shortcut for binding a callback to be run after a route is executed. After callbacks have no guarunteed order.

around ( callback )

Adds an around filter to the application. around filters are functions that take a single argument callback which is the entire route execution path wrapped up in a closure. This means you can decide whether or not to proceed with execution by not invoking callback or, more usefuly wrapping callback inside the result of an asynchronous execution.

Example

The most common use case for around() is calling a possibly async function and executing the route within the functions callback:

before ( options, callback )

Takes a single callback that is pushed on to a stack. Before any route is run, the callbacks are evaluated in order within the current Sammy.EventContext

If any of the callbacks explicitly return false, execution of any further callbacks and the route itself is halted.

You can also provide a set of options that will define when to run this before based on the route it proceeds.

Example

See contextMatchesOptions() for a full list of supported options

bind ( name, data, callback )

Works just like jQuery.fn.bind() with a couple noteable differences.

  • It binds all events to the application element
  • All events are bound within the eventNamespace()
  • Events are not actually bound until the application is started with run()
  • callbacks are evaluated within the context of a Sammy.EventContext

See code.quirkey.com/sammy/docs/events.html for more info.

bindToAllEvents ( callback )

Will bind a single callback function to every event that is already being listened to in the app. This includes all the APP_EVENTS as well as any custom events defined with bind().

Used internally for debug logging.

contextMatchesOptions ( context, match_options, positive )

Matches an object of options against an EventContext like object that contains path and verb attributes. Internally Sammy uses this for matching before() filters against specific options. You can set the object to only match certain paths or verbs, or match all paths or verbs except those that match the options.

Example

error ( message, original_error )

The base error handler takes a string message and an Error object. If raise_errors is set to true on the app level, this will re-throw the error to the browser. Otherwise it will send the error to log(). Override this method to provide custom error handling e.g logging to a server side component or displaying some feedback to the user.

eventNamespace ( )

A unique event namespace defined per application. All events bound with bind() are automatically bound within this space.

getLocation ( )

Delegates to the location_proxy to get the current location. See Sammy.HashLocationProxy for more info on location proxies.

helper ( name, method )

Helper extends the event context just like helpers() but does it a single method at a time. This is especially useful for dynamically named helpers

Example

Arguments

name:The name of the method
method:The function to be added to the prototype at name

helpers ( extensions )

Helpers extends the EventContext prototype specific to this app. This allows you to define app specific helper functions that can be used whenever you’re inside of an event context (templates, routes, bind).

Example

Arguments

extensions:An object collection of functions to extend the context.

isRunning ( )

Returns a boolean of weather the current application is running.

lookupRoute ( verb, path )

Given a verb and a String path, will return either a route object or false if a matching route can be found within the current defined set.

mapRoutes ( route_array )

mapRoutes takes an array of arrays, each array being passed to route() as arguments, this allows for mass definition of routes. Another benefit is this makes it possible/easier to load routes via remote JSON.

Example

notFound ( verb, path )

This thows a ‘404 Not Found’ error by invoking error(). Override this method or error() to provide custom 404 behavior (i.e redirecting to / or showing a warning)

refresh ( )

Reruns the current route

routablePath ( path )

Returns a copy of the given path with any query string after the hash removed.

route ( verb, path, callback )

route() is the main method for defining routes within an application. For great detail on routes, check out: code.quirkey.com/sammy/doc/routes.html

This method also has aliases for each of the different verbs (eg. get(), post(), etc.)

Arguments

verb:A String in the set of ROUTE_VERBS or ‘any’. ‘any’ will add routes for each of the ROUTE_VERBS. If only two arguments are passed, the first argument is the path, the second is the callback and the verb is assumed to be ‘any’.
path:A Regexp or a String representing the path to match to invoke this verb.
callback:A Function that is called/evaluated whent the route is run see: runRoute(). It is also possible to pass a string as the callback, which is looked up as the name of a method on the application.

run ( start_url )

Actually starts the application’s lifecycle. run() should be invoked within a document.ready block to ensure the DOM exists before binding events, etc.

Example

Arguments

start_url:“value”, Optionally, a String can be passed which the App will redirect to after the events/routes have been bound.

runRoute ( verb, path, params )

First, invokes lookupRoute() and if a route is found, parses the possible URL params and then invokes the route’s callback within a new Sammy.EventContext. If the route can not be found, it calls notFound(). If raise_errors is set to true and the error() has not been overriden, it will throw an actual JS error.

You probably will never have to call this directly.

Arguments

verb:A String for the verb.
path:A String path to lookup.
params:An Object of Params pulled from the URI or passed directly.

Returns

Either returns the value returned by the route callback or raises a 404 Not Found error.

setLocation ( new_location )

Delegates to the location_proxy to set the current location. See Sammy.HashLocationProxy for more info on location proxies.

Arguments

new_location:A new location string (e.g. ’#/’)

swap ( content )

Swaps the content of $element() with content You can override this method to provide an alternate swap behavior for EventContext.partial().

Example

toString ( )

//=> Sammy.Application: body

trigger ( name, data )

Triggers custom events defined with bind()

Arguments

name:The name of the event. Automatically prefixed with the eventNamespace()
data:An optional Object that can be passed to the bound callback.
context:An optional context/Object in which to execute the bound callback. If no context is supplied a the context is a new Sammy.EventContext

unload ( )

The opposite of run(), un-binds all event listeners and intervals run() Automaticaly binds a onunload event to run this when the document is closed.

use ( )

use() is the entry point for including Sammy plugins. The first argument to use should be a function() that is evaluated in the context of the current application, just like the app_function argument to the Sammy.Application constructor.

Any additional arguments are passed to the app function sequentially.

For much more detail about plugins, check out: code.quirkey.com/sammy/doc/plugins.html

Example

Sammy.EventContext ( app, verb, path, params )

Sammy.EventContext objects are created every time a route is run or a bound event is triggered. The callbacks for these events are evaluated within a Sammy.EventContext This within these callbacks the special methods of EventContext are available.

Example

Initialize a new EventContext

Arguments

app:The Sammy.Application this event is called within.
verb:The verb invoked to run this context/route.
path:The string path invoked to run this context/route.
params:An Object of optional params to pass to the context. Is converted to a Sammy.Object.

Methods


( )

Split interpolated strings into an array of literals and code fragments.

( )

Parse the attribute block using a state machine

$element ( )

A shortcut to the app’s $element()

eventNamespace ( )

A shortcut to app’s eventNamespace()

notFound ( )

Raises a possible notFound() error for the current path.

partial ( path, data, callback )

Used for rendering remote templates or documents within the current application/DOM. By default Sammy and partial() know nothing about how your templates should be interpeted/rendered. This is easy to change, though. partial() looks for a method in EventContext that matches the extension of the file you’re fetching (e.g. ‘myfile.template’ will look for a template() method, ‘myfile.haml’ => haml(), etc.) If no matching render method is found it just takes the file contents as is.

If you’re templates have different (or no) extensions, and you want to render them all through the same engine, you can set the default/fallback template engine on the app level by setting app.template_engine to the name of the engine or a function() {}

Caching

If you use the Sammy.Cache plugin, remote requests will be automatically cached unless you explicitly set cache_partials to false

Example

There are a couple different ways to use partial():

Iteration/Arrays

If the data object passed to partial() is an Array, partial() will itterate over each element in data calling the callback with the results of interpolation and the index of the element in the array.

redirect ( )

Changes the location of the current window. If to begins with ’#’ it only changes the document’s hash. If passed more than 1 argument redirect will join them together with forward slashes.

Example

swap ( contents )

A shortcut to app’s swap()

toString ( )

//=> Sammy.EventContext: get #/ {}

trigger ( name, data )

Triggers events on app within the current context.

Sammy.Haml ( app, method_alias )

Sammy.Haml provides a quick way of using haml style templates in your app. The plugin itself includes the haml-js library created by Tim Caswell at at github.com/creationix/haml-js

Haml is an alternative HTML syntax that is really great for describing the structure of HTML documents.

By default using Sammy.Haml in your app adds the haml() method to the EventContext prototype. However, just like Sammy.Template you can change the default name of the method by passing a second argument (e.g. you could use the hml() as the method alias so that all the template files could be in the form file.hml instead of file.haml)

Example

The template (mytemplate.haml):

The app:

If I go to #/hello/AQ in the browser, Sammy will render this to the body:

Note: You dont have to include the haml.js file on top of the plugin as the plugin includes the full source.

Sammy.JSON ( app )

Sammy.JSON is a simple wrapper around Douglas Crockford’s ever-useful json2.js (www.json.org/js.html]) Sammy.JSON includes the top level JSON object if it doesn’t already exist (a.k.a. does not override the native implementation that some browsers include). It also adds a json() helper to a Sammy app when included.

Methods


create_context ( _context )

by @langalex, support for arrays of strings

json ( object )

json is a polymorphic function that translates objects aback and forth from JSON to JS. If given a string, it will parse into JS, if given a JS object it will stringify into JSON.

Example

Sammy.Mustache ( app, method_alias )

Sammy.Mustache provides a quick way of using mustache style templates in your app. The plugin itself includes the awesome mustache.js lib created and maintained by Jan Lehnardt at github.com/janl/mustache.js

Mustache is a clever templating system that relys on double brackets for interpolation. For full details on syntax check out the original Ruby implementation created by Chris Wanstrath at github.com/defunkt/mustache

By default using Sammy.Mustache in your app adds the mustache() method to the EventContext prototype. However, just like Sammy.Template you can change the default name of the method by passing a second argument (e.g. you could use the ms() as the method alias so that all the template files could be in the form file.ms instead of file.mustache)

Example #1

The template (mytemplate.ms):

The app:

If I go to #/hello/AQ in the browser, Sammy will render this to the body:

Example #2 - Mustache partials

The template (mytemplate.ms)

The partial (mypartial.ms)

The app:

If I go to #/hello/AQ/to/dP in the browser, Sammy will render this to the body:

Note: You dont have to include the mustache.js file on top of the plugin as the plugin includes the full source.

Sammy.NestedParams ( app )

Sammy.NestedParams overrides the default form parsing behavior to provide extended functionality for parsing Rack/Rails style form name/value pairs into JS Objects. In fact it passes the same suite of tests as Rack’s nested query parsing. The code and tests were ported to JavaScript/Sammy by github.com/endor

This allows you to translate a form with properly named inputs into a JSON object.

Example

Given an HTML form like so:

And a Sammy app like:

If you filled out the form with some values and submitted it, you would see something like this in your log:

It supports creating arrays with [] and other niceities. Check out the tests for full specs.

Sammy.Store ( options )

Sammy.Store is an abstract adapter class that wraps the multitude of in browser data storage into a single common set of methods for storing and retreiving data. The JSON library is used (through the inclusion of the Sammy.JSON) plugin, to automatically convert objects back and forth from stored strings.

Sammy.Store can be used directly, but within a Sammy.Application it is much easier to use the Sammy.Storage plugin and its helper methods.

Sammy.Store also supports the KVO pattern, by firing DOM/jQuery Events when a key is set.

Example

Arguments

The constructor takes a single argument which is a Object containing these possible options.

name:The name/namespace of this store. Stores are unique by name/type. (default ‘store’)
element:A selector for the element that the store is bound to. (default ‘body’)
type:The type of storage/proxy to use (default ‘memory’)

Extra options are passed to the storage constructor. Sammy.Store supports the following methods of storage:

memory:Basic object storage
data:jQuery.data DOM Storage
cookie:Access to document.cookie. Limited to 2K
local:HTML5 DOM localStorage, browswer support is currently limited.
session:HTML5 DOM sessionStorage, browswer support is currently limited.

Methods


clear ( key )

Removes the value at key from the current store

clearAll ( )

Clears all the values for the current store.

exists ( key )

Checks for the existance of key in the current store. Returns a boolean.

fetch ( key, callback )

Returns the value at key if set, otherwise, runs the callback and sets the value to the value returned in the callback.

Example

get ( key )

Returns the set value at key, parsing with JSON.parse and turning into an object if possible

isAvailable ( )

Checks for the availability of the current storage type in the current browser/config.

keys ( )

Returns the all the keys set for the current store as an array. Internally Sammy.Store keeps this array in a ‘meta_key’ for easy access.

load ( key, path, callback )

loads the response of a request to path into key.

Example

In /mytemplate.tpl:

In app.js:

set ( key, value )

Sets the value of key<tt> with <tt>value. If value<tt> is an object, it is turned to and stored as a string with <tt>JSON.stringify. It also tries to conform to the KVO pattern triggering jQuery events on the element that the store is bound to.

Example

Sammy.Store.isAvailable ( type )

Tests if the type of storage is available/works in the current browser/config. Especially useful for testing the availability of the awesome, but not widely supported HTML5 DOM storage

Sammy.Store.Memory ( name, element )

Memory (‘memory’) is the basic/default store. It stores data in a global JS object. Data is lost on refresh.

Sammy.Store.Data ( name, element )

Data (‘data’) stores objects using the jQuery.data() methods. This has the advantadge of scoping the data to the specific element. Like the ‘memory’ store its data will only last for the length of the current request (data is lost on refresh/etc).

Sammy.Store.LocalStorage ( name, element )

LocalStorage (‘local’) makes use of HTML5 DOM Storage, and the window.localStorage object. The great advantage of this method is that data will persist beyond the current request. It can be considered a pretty awesome replacement for cookies accessed via JS. The great disadvantage, though, is its only available on the latest and greatest browsers.

For more info on DOM Storage: [developer.mozilla.org/en/DOM/Storage] [www.w3.org/TR/2009/WD-webstorage-20091222/]

Sammy.Store.SessionStorage ( name, element )

.SessionStorage (‘session’) is similar to LocalStorage (part of the same API) and shares similar browser support/availability. The difference is that SessionStorage is only persistant through the current ‘session’ which is defined as the length that the current window is open. This means that data will survive refreshes but not close/open or multiple windows/tabs. For more info, check out the LocalStorage documentation and links.

Sammy.Store.Cookie ( name, element, options )

.Cookie (‘cookie’) storage uses browser cookies to store data. JavaScript has access to a single document.cookie variable, which is limited to 2Kb in size. Cookies are also considered ‘unsecure’ as the data can be read easily by other sites/JS. Cookies do have the advantage, though, of being widely supported and persistent through refresh and close/open. Where available, HTML5 DOM Storage like LocalStorage and SessionStorage should be used.

.Cookie can also take additional options:

expires_in:Number of seconds to keep the cookie alive (default 2 weeks).
path:The path to activate the current cookie for (default ’/’).

For more information about document.cookie, check out the pre-eminint article by ppk: [www.quirksmode.org/js/cookies.html]

Sammy.Storage ( app )

Sammy.Storage is a plugin that provides shortcuts for creating and using Sammy.Store objects. Once included it provides the store() app level and helper methods. Depends on Sammy.JSON (or json2.js).

Sammy.Session ( app, options )

Sammy.Session is an additional plugin for creating a common ‘session’ store for the given app. It is a very simple wrapper around Sammy.Storage that provides a simple fallback mechanism for trying to provide the best possible storage type for the session. This means, LocalStorage if available, otherwise Cookie, otherwise Memory. It provides the session() helper through Sammy.Storage#store().

See the Sammy.Storage plugin for full documentation.

Sammy.Cache ( app, options )

Sammy.Cache provides helpers for caching data within the lifecycle of a Sammy app. The plugin provides two main methods on Sammy.Application<tt>, <tt>cache and clearCache. Each app has its own cache store so that you dont have to worry about collisions. As of 0.5 the original Sammy.Cache module has been deprecated in favor of this one based on Sammy.Storage. The exposed API is almost identical, but Sammy.Storage provides additional backends including HTML5 Storage. Sammy.Cache will try to use these backends when available (in this order) LocalStorage, SessionStorage, and Memory

Sammy.Template ( app, method_alias )

Sammy.Template is a simple plugin that provides a way to create and render client side templates. The rendering code is based on John Resig’s quick templates and Greg Borenstien’s srender plugin. This is also a great template/boilerplate for Sammy plugins.

Templates use <% %> tags to denote embedded javascript.

Examples

Here is an example template (user.template):

Given that is a publicly accesible file, you would render it like:

You can also pass a second argument to use() that will alias the template method and therefore allow you to use a different extension for template files in partial()

Feel free to email me at aaron at quirkey dot com.

Please check out my blog.

If you like or use this library – I don’t want donations – but you can recommend me on workingwithrails.com or hire me to work on your next project.