Let’s expand on the previous post Single Page Apps – Getting Started with SammyJS – Routes and create a form using Sammy.js. Instead of adding HTML inline, we can use an external template. And because the data for the input form is contained on a single page, we can display the data on what appears to the user to be another page, after the user submits the form.
This topic introduces how you can use Sammy.EventContext object. The Sammy.EventContext is created every time a route is run or a bound event is triggered. The callbacks for these events are evaluated within a
- partial (location, data, callback, partials) Gets a partial HTML page from a file, takes the data (if any) and pass it to the partial page, and then swap out the app’s element with the rendered content.
- render (location, data, callback, partials) Is like the partial, except it does not swap out the page. You attach the rendered item in the DOM.
- redirect () Changes the current window to the new location. If the redirect includes a hash, then it only changes the same page’s URL with the hash.
- load ( location, options, callback ) create a new
options. Called without interpolation or placement, this allows for preloading/caching the templates or data.
Sammy Form Sample
The following sample, written by Aaron Quint, shows an implementation of a form. It loads a form using Sammy’s partial() method. During the post, it saves the data into the form_fields var that is inside your app object. Then completes the post by redirect() to the display hash where the form_fields var is displayed.
The sample uses the following form template named 2-Form.html in the Files folder.
The section labeled “Plain old form” shows you can submit the post directly back to the server.
Sample code for this post is available on DevDays GitHub: https://github.com/devdays/single-page-app/tree/master/Sammy
Sammy.EventContext in Sammy API Documentation