How can I pass query string to backbone.js routing

瘦欲@ 提交于 2019-12-21 03:44:23

问题


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.



来源:https://stackoverflow.com/questions/9966958/how-can-i-pass-query-string-to-backbone-js-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!