Pass an argument when routing through a view in backbone.js - javascript

I want to pass an argument when routing in a Backbone.js application
Here is the transcript
var AppRouter = Backbone.Router.extend({
routes: {
'toolSettings/(:action)' : 'toolSettings'
}
});
var initialize = function() {
var app_router = new AppRouter;
app_router.on('route:toolSettings', function(actions) {
toolSettingsRoute.route();
});
Backbone.history.start();
};
On the UI I've a <a href="toolSettings/target" /> link which would invoke the toolSettingsRoute.route().
I want pass this action argument in the route method and i've to pass it to further proceedings.
I tried toolSettingsRoute.route(action) and it's not giving any error, though how do i use this argument in the toolSettingsRoute.js file
I'd like to know how we can pass arguments correctly and utilize them in the subsequent js

One options is to define your route functions in your router and you can just pass the parameter in to that function:
var AppRouter = Backbone.Router.extend({
routes: {
'toolSettings/(:action)': 'toolSettings'
},
toolSettings: function (action) {
// whatever
}
});

E X A M P L E
http://jsfiddle.net/mreis1/Nt9tm/1/
var AppRouter = Backbone.Router.extend({
routes: {
'toolSettings/:action' : 'toolSettings'
},
toolSettings:function (action){
//do whatever you want to do with the action parameter
}
});

Related

How to catch query param changes with Backbone.Router?

I have the following Backbone.Route:
var CustomRoute = Backbone.Router.extend({
routes: {
"/search": "onChangeUrl"
},
onChangeUrl: function (query, page) {
// handle event
}
});
Backbone.history.start({pushState: true});
And the following url: http://www.mysite_.com/search?name=erik&age=34
How could I handle event on changing any query params?
You need define two routers, like so
var CustomRoute = Backbone.Router.extend({
routes: {
'search': 'onChangeUrl',
'search?*query': 'onChangeUrl'
},
onChangeUrl: function (query) {
// handle event
}
});
Example

Get Current URL with query parameters in Backbone Marionette

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()
});
});
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.
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"

Strict parameter matching in backbone.js router

I've got a router defined as such:
var MyRouter = Backbone.Router.extend({
routes: {
// catch-all for undefined routes
"*notfound" : "notFound",
},
initialize: function(options) {
this.route("my_resource/clear_filters", 'clearFilters');
this.route("my_resource/:id", 'show');
},
show: function(id){
console.log('show', id);
},
clearFilters: function() {
console.log('clearFilters');
},
notFound: function() {
console.log('notFound');
},
});
var app = {};
app.MyRouter = new MyRouter();
Backbone.history.start({silent: true});
Thus the following URLs would map as:
var opts = {trigger: true};
app.MyRouter.navigate('/foo', opts); // logged -> 'notFound'
app.MyRouter.navigate('/my_resource/123', opts); // logged -> 'show', '123'
app.MyRouter.navigate('/my_resource/clear_filters', opts); // logged -> 'clearFilters'
app.MyRouter.navigate('/my_resource/some_thing', opts); // logged -> 'show', 'some_thing'
How can I restrict the my_resource/:id route to only match on numeric parameters so that app.MyRouter.navigate('/my_resource/some_thing') is handled by notFound?
From the fine manual:
route router.route(route, name, [callback])
Manually create a route for the router, The route argument may be a routing string or regular expression. Each matching capture from the route or regular expression will be passed as an argument to the callback.
So you can always say things like:
this.route(/my_resource\/(\d+)/, 'show')
in your router's initialize if you need finer grained control over the routes than Backbone's string patterns give you.

Setting up Backbone router

Can't figure out what's going wrong with my Backbone router. Can anyone spot a mistake in the following block of code? The index route is working fine but the classes route isn't ever triggering (e.g. when I navigate to a URL like localhost/classes/test)
var app = app || {};
$(function() {
app.Router = Backbone.Router.extend({
routes: {
'' : 'index',
'classes/:id' : 'classes'
},
initialize: function() {
this.classList = new app.ClassCollection();
},
index: function() {
this.menuView = new app.ClassCollectionView({collection: this.classList});
},
classes: function(id) {
console.log("hello")
var _class = new app.ClassModel({id: id});
this.classView = new app.ClassPageView({model: _class});
}
});
router = new app.Router();
Backbone.history.start({pushState: true});
})
If everything looks in order, there's probably a bug somewhere else in my code.
Backbone.router is extending hashbang navigation.
so
localhost/#classes/test
should lead to your method. ALSO! pay attention that emty route should be at the end of the routes list.
It's like else if construction, if route matches "" (default # ?!) it will never match other routes
by default the route will work with the hash try localhost/#classes/test

Name space my backbone models

I currently set out my models like this:
var Contact = Backbone.Model.extend({
defaults: {
photo: "img/placeholder.png",
name: "",
address: "",
tel: "",
email: "",
type: ""
}
});
and my collection like so:
var Directory = Backbone.Collection.extend({
model: Contact
});
Then in my main app.js file, I'm doing this to define my routes:
var AppRouter = Backbone.Router.extend({
initialize:function () {
$('#header').html(new HeaderView().render().el);
},
routes: {
"filter/:type": "urlFilter"
},
urlFilter: function (type) {
directory.filterType = type;
directory.trigger("change:filterType");
},
});
I'm getting an error with the code below which tells me 'directory' is undefined.
directory.filterType = type;
directory.trigger("change:filterType");
In my view I new up the collection like so, this.collection = new Directory(contacts);
I'm pretty new to backbone and I'm not sure if Im doing things in the correct order, and that my collection doesn't exist at the time when I'm trying to do my filterType and Trigger or wether I have things completely wrong.
My code can be viewed here, http://dan.ms/backbone
Any pointers gratefully received.
The directory variable seems to be created in a callback to tpl.loadTemplates. The variable is not available in the scope where it's being accessed inside your router. One way to do it would be to pass directory to the AppRouter constructor as a parameter. In AppRouter's constructor, save it as a property, and access it in the urlFilter method via the current instance.
var AppRouter = Backbone.Router.extend({
initialize: function (options) {
this.directory = options.directory;
},
urlFilter: function (type) {
this.directory.set("filterType", type);
}
});
// Initialize with:
var directory = new DirectoryView;
var app = new AppRouter({ directory: directory });
Backbone.history.start();

Categories