如何将查询字符串传递给backbone.js路由

Pre*_*vLe 15 url-routing query-string backbone.js

我正在使用Backbone.js和jQuery-mobile.jQuery-mobile routing被禁用,我只使用lib进行UI.除了选择页面转换外,我完成了所有工作.我需要将页面转换('slice-up','fade','slide-down')传递给Backbone路由器,因为转换是根据用户来自何处而变化的.

我已经想出了一个非常难看的方法,通过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)
Run Code Online (Sandbox Code Playgroud)

这是默认转换的html链接:

<a href="#" data-icon="back" class="ui-btn-left">Back</a>
Run Code Online (Sandbox Code Playgroud)

这是淡入淡出过渡的html链接:

<a href="#fade" data-icon="back" class="ui-btn-left">Back</a>
Run Code Online (Sandbox Code Playgroud)

使用查询字符串,即/ food/new?transition ='fade'肯定更好,但我不知道如何定义骨干路由以使用查询字符串变量.

我该怎么做?

是否有一种更优雅的方式来处理我的问题,即传递变量而不使用url?

abr*_*ham 12

您必须手动解析路由器功能中的URL参数.

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'))
Run Code Online (Sandbox Code Playgroud)

JS函数解析查询参数.

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;
}
Run Code Online (Sandbox Code Playgroud)

你当然必须将JS函数转换为CS,但你明白了.

  • `unescape`在2012年?我建议在历史垃圾箱中留下`escape`和`unescape`,`encodeURIComponent`和[`decodeURIComponent`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURIComponent)通常是什么你想用. (7认同)
  • 我发现这个骨干插件完全符合我的需要!https://github.com/jhudson8/backbone-query-parameters (6认同)