How can I pass query string to backbone.js routing

2020-06-09 04:58发布

问题:

I'm using Backbone.js and jQuery-mobile. jQuery-mobile routing is disabled and I'm using the lib only for UI. I got everything working, except selecting page transition. I need to pass the page transition ('slice-up', 'fade', 'slide-down') to the Backbone router because the transition is varying based on where the user comes from.

I have figured a very ugly way to do it, to pass them via the url:

class App.Routers.Foods extends Backbone.Router
  routes:
    '': 'index'
    ':transition': 'index'
    'foods/new': 'new'
    'foods/new/:transition': 'new'

  initialize: ->
    @collection = new App.Collections.Foods()
    @collection.fetch()

  index: (transition)->
    view = new App.Views.FoodIndex(collection: @collection)
    App.changePage(view, transition)

  new: (transition)->
    view = new App.Views.FoodNew(collection: @collection)
    App.changePage(view, transition)

Here is the html link for default transition:

<a href="#" data-icon="back" class="ui-btn-left">Back</a>

Here is the html link for fade transition:

<a href="#fade" data-icon="back" class="ui-btn-left">Back</a>

Using the query string, i.e. /food/new?transition='fade' is definitely better but I don't know how to define the backbone routing to use query string variables.

How should I do this?

Is there a more elegant way to handle my problem, i.e. passing the variable not using the url at all?

回答1:

You will have to manually parse the URL parameter inside the router functions.

class App.Routers.Foods extends Backbone.Router
  routes:
    '': 'index'
    'foods/new': 'new'

  initialize: ->
    @collection = new App.Collections.Foods()
    @collection.fetch()

  index: ()->
    view = new App.Views.FoodIndex(collection: @collection)
    App.changePage(view, getQueryVariable('transition'))

  new: ()->
    view = new App.Views.FoodNew(collection: @collection)
    App.changePage(view, getQueryVariable('transition'))

JS function to parse query params.

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return unescape(pair[1]);
        }
    }
    return false;
}

You will of course have to convert the JS function to CS but you get the idea.