Backbone.js URI Sync Adapter

I am working on a backbone based search page, and was trying to figure out what would be a simple way to have both a state model and a URI that represents that state of the page (the search string, search parameters, user preferences, etc.).

Thinking of mixing backbone routes and the application models seemed like an overkill, and would force me to handle everything through a route or an event.

After a short struggle, I realized that the best case would be to have a model that keeps me in model land, but has the representation in the URI, and came out with Backbone URI Storage.

The concept is very simple, and works like charm – use a standard backbone model, enjoy data binding, and simply hook the model in the URI.

var State = Backbone.Model.extend({
    sync: uriSync
});
var Search = Backbone.Model.extend({
    url: '/rest/v1/search/';
});

And now, I can update the application state when my search changes:

var state = new State({id: 'search-page'});
var search = new Search();
search.on('change', function(){
    state.save(search.toJSON());
});

A working code example can be found here.

Its as simple as that!

Leave a Reply

Your email address will not be published. Required fields are marked *