1

URL : http://localhost:3000/dashboard?ID=10400&Name=10400

I'm trying to get the query params ID and Name from the URL but I get undefined. I have also tried backbone-queryparams but still it does not work. Any idea how to get the current URL with params in Backbone Marionette

define([
    'jquery',
    'backbone',
    'marionette',       
    'modules/dashboard/controllers/dashboardController',
    'backbone.queryparmas'
], function ($, Backbone, Marionette, Controller) {
    'use strict';

    return Marionette.AppRouter.extend({

        appRoutes: {
            '': 'dashboard'
        },

        initialize: function(){
            console.log( Backbone.history.fragment ); // getting undefined
        },

        controller: new Controller()
    });

});
Srikanth Jeeva
  • 3,005
  • 4
  • 38
  • 58

2 Answers2

1

I had to do this to get the query params. Not sure if there is any better way.

messagedashboard: function () {
  var searchParams = window.location.search.slice(1); // returns 'ID=10400&Name=10400'
  var getParamsFromSearchParams = $.deparam(searchParams); //changes into object
}

For using $.deparam check jquery.bbq library.

Srikanth Jeeva
  • 3,005
  • 4
  • 38
  • 58
  • this does not seem to work when the url is `domain.com/#path?query=param`. The `window.location.search` slice returns an empty string for me – mix3d Jun 23 '17 at 18:50
1

From the example here (https://stackoverflow.com/a/11671457/3780922), it looks like the best option is to set a route with a catchall parameter, which will give you the entire query string.

appRoutes: {
   '': 'showDash', //default for blank/empty route
   'dashboard': 'showDash',
   'dashboard?*queryString' : 'showDash'
},
showDash: function (queryString) {
    var params = parseQueryString(queryString);
    if(params.foo){
        // foo parameters was passed
    }
}

You'll have to write your own query string parser, however, but if it is not null, then you have your query parameter passed in the queryString object, which in your example would be "ID=10400&Name=10400"

Community
  • 1
  • 1
mix3d
  • 4,122
  • 2
  • 25
  • 47