documentcloud / visualsearch

A Rich Search Box for Real Data
http://documentcloud.github.com/visualsearch
MIT License
1.8k stars 237 forks source link

Support permalinks / browser history (via routers) #73

Closed brycecorkins closed 11 years ago

brycecorkins commented 12 years ago

Been trying to get VisualSearch to update the URL bar when a search is entered, and to execute a search based on the current url, but I'm new to backbone and can't figure it out. Any suggestions on how to do this?

samuelclay commented 11 years ago

I would hook into the callbacks on search and then just manually hit your backbone router to update the url. In the other direction, have your router instantiate the search box with the query you extract from the url. Handle it manually, but use the search callback provided.

brycecorkins commented 10 years ago

Following up with the solution:

search:       function(query, searchCollection) {

    // Update routers
    var searchdata = [];
    var searchuri = 'search/';
    searchdata = searchCollection.facets();

    // Build the search URI
    for(var i = 0; i < searchdata.length; i++) {
        $.each(searchdata[i], function(k, v) {
            searchdata[i][k] = searchdata[i][k].replace('&','\%and');
        });
        searchuri = searchuri + $.param(searchdata[i]);
        if(i < (searchdata.length - 1)) {
            searchuri = searchuri + "&";
        }
    }

    VS.app.searcher.navigate("/" + searchuri);

...

Then outside the VS.init function:

VS.utils.Searcher = Backbone.Router.extend({
    routes: {
        "search/:query": "search"  // matches http://site.com/#search/query
    },
    search: function(query) {

        if(!query) {
            return;
        }
        var result = new Array();

        query = query.replace(/\+/g, ' ');

        $.each(query.split('&'), function(index, value){
            if(value){
                value = value.replace('%and','&');
                result.push(value);
            }
        });

        visualSearch.searchBox.value('');

        $.each(result, function(index, value) {
            var param = value.split('=');
            visualSearch.searchBox.addFacet(param[0], param[1], 99);
        });

        visualSearch.searchBox.searchEvent({});
    }
});
// Initiate the router
VS.app.searcher = new VS.utils.Searcher;

// Start Backbone history a necessary step for bookmarkable URL's
Backbone.history.start();