Documentation

Events

Inside of a Sammy application javascript events can be defined, bound and triggered. The methods for doing this purposely look identical to the jQuery Event API. Though they look the same their function is slightly different.

Bind

Custom events can be bound within the application definition block with the bind() method.


      // bind(name, callback)
      bind('db-loaded', function(e, data) {
        this.redirect('#/');
      });
      

Internally, Sammy binds the events to the application element within a unique application namespace. This means that if you have two Sammy applications running in the same document, you can trigger and bind events without worrying about double-trigger issues. Events are also automatically bound and unbound to the DOM on run() and unload().

Inside of the callback, this is a Sammy.EventContext just like it is for routes. This means you can redirect, partial, etc.

Trigger

The other side of events is trigger() which triggers the custom events you’ve defined. trigger() works within both the context of the app and other events/routes.

These triggers are equivalent:


      var app = $.sammy(function() {
        
        bind('test', function() {
          // trigger on EventContext
          this.trigger('other-event');
        });
        
      });
      
      // trigger on the app itself
      app.trigger('other-event');
      

You can also pass a custom data object to trigger. These get passed to the bound callback as the second argument.


      var app = $.sammy(function() {
        
        bind('test', function(e, data) {
          alert(data['my_data']);
        });
        
        get('#/', function() {
          this.trigger('test', {my_data: 'EVENTED!'});
        });
        
      });
      

With this example, taking our browser to #/ would fire the event 'test' passing and alerting our precious data.

Pre-defined Events

Sammy applications have a number of predefined events that are fired throughout an app’s life cycle. It’s often useful to bind/listen to these existing events in order to invoke functionality at particular points.

The most common use case is listening to run. run is the first event fired in the app’s lifecycle and can be useful for establishing a connection to a database, build out a list of documents, etc.

To see a list of all the pre-defined events, check the API