How to do a route alias within a Backbone Router? - javascript

Having a route like 'dogs': 'process', I need to rewrite it to 'animals': 'process'.
Now, I need the router to recognize both routes, but always display the url like /animals, it is sort of aliasing, but could not find any info on how to solve this without placing an url redirect in 'process' handler.

I'm assuming that the real need for aliases is different than dogs to animals, so I'll answer regardless of if the use-case here is good or not. But if you don't want to change the hash but want to trigger different behaviors in the app, using the router is probably not the route to go.
Route aliases don't really exist in Backbone, other than defining different routes using the same callback. Depending on your exact use-case, there are multiple ways to handle similar routes.
Replace the hash
To display the same hash for a generic route coming from different routes, use the replace option of the navigate function.
routes: {
'lions': 'animalsRoute',
'animals': 'animalsRoute'
},
animalsRoute: function() {
this.navigate("#/animals", { replace: true });
// or using the global history object:
// Backbone.history.navigate("#/animals", { replace: true });
}
then handle the animals route, regardless of which route was initially used to get in this callback.
Some other answers or tutorials will say to use window.location.hash but don't. Manually resetting the hash will trigger the route regardless and may cause more trouble than it'll help.
Different behaviors but showing the same route
Just use different callbacks, both using the replace trick above.
routes: {
'lions': 'lionsRoute',
'tigers': 'tigersRoute'
},
showGenericRoute: function() {
this.navigate("#/animals", { replace: true });
},
tigersRoute: function() {
this.showGenericRoute();
// handle the tigers route
},
lionsRoute: function() {
this.showGenericRoute();
// handle the lions route
}
Notice the inexistent animalsRoute. You could add the route if there's a generic behavior if no specific animal is chosen.
Use the route params
If you want to know which animal was chosen but still use the same callback and remove the chosen animal from the hash, use the route params.
routes: {
'animals/:animal': 'animalsRoute',
},
animalsRoute: function(animal) {
// removes the animal from the url.
this.navigate("#/animals", { replace: true });
// use the chosen animal
var view = new AnimalView({ type: animal });
}
Redirect to the generic route
If you want a different behavior but always show the same route, use different callbacks, then redirect. This is useful if the generic route is in another router instance.
var Router = Backbone.Router.extend({
routes: {
'animals': 'animalsRoute'
},
animalsRoute: function() {
// handle the generic behavior.
}
});
var PussyRouter = Backbone.Router.extend({
routes: {
'lions': 'lionsRoute'
// ...
},
lionsRoute: function() {
// handle lions, then redirect
this.navigate("#/animals", { trigger: true, replace: true });
}
});
Using the trigger options will call the animalsRoute in the other router and the replace option will avoid making an entry in the history, so pushing the back button won't go to lions to get back to animals and being caught in the animals route.

Related

Angular: Reference query params in redirectTo

I would like to provide a path that redirects to a given page based on query parameters. For example:
/redirect?page=hero&id=1
should redirect to:
/hero/1
Is there any way to do this in the route config? Something like:
{ path: 'redirect?page&id', redirectTo: ':page/:id' }
I can get the redirectTo to respect path parameters but not query parameters. Any ideas?
You can try to use redirectTo: '/:page/:id' and provide extracted from your URL page and id values using custom UrlMatcher():
...
const appRoutes: Routes = [
{
path: 'hero/:id',
component: TestComponent
},
{
matcher: redirectMatcher,
redirectTo: '/:page/:id'
}
];
...
/**
* custom url matcher for router config
*/
export function redirectMatcher(url: UrlSegment[]) {
if (url[0] && url[0].path.includes('redirect')) {
const path = url[0].path;
// sanity check
if (path.includes('page') && path.includes('id')) {
return {
consumed: url,
posParams: {
page: new UrlSegment(path.match(/page=([^&]*)/)[1], {}),
id: new UrlSegment(path.match(/id=([^&]*)/)[1], {})
}
}
}
}
return null;
}
STACKBLITZ: https://stackblitz.com/edit/angular-t3tsak?file=app%2Ftest.component.ts
There is another issue when using redirectTo: ..., active link is not updated, actually isActive flag is not set to true, it is seen on my stackblitz when acrive redirection links are not colored in red
No, there is no way of doing it by a configuration. YOu see, Angular's router does not explicitly define query parameters - any url can have an arbitrary number of query params, and the paths '/page/id' and '/page/id?key=value' are treated as the same in Angular and do map to the same component. There are other, more cumbersome workarounds. One is to create a dummy component and redirect based on ActivatedRoute.queryParams Observable from the component's ngOnInit method. You can easily see why this is a bad idea.
Another way is to create a resolver, this way you maybe can dismiss the component declaration and just redirect from the resolver, again, based on the ActivatedRoute.queryParams Observable, which seems cleaner.
But I do not really get why one would need such a route in a front end application, if you want someone to visit '/page/id', then just navigate them to the page, without any intermediary tricks.

Ember not calling setupController of router

So, I have two paths in my route. I created the two routes as the doc recommends.
My router is the following:
// router.js
Router.map(function() {
this.route('photos');
this.route('photo', { path: '/photo/:photo_id' });
});
If I visit firstly the route /photo/ID and then go to /photos, it will only show one object on the latter. (wrong)
If I visit /photos first it shows all the objects and I can go to /photo/ID later on and it will be fine. (right)
I want to make it work both ways. How to do this? You can see my code for each route down below:
// photo.js
export default Ember.Route.extend({
model(params) {
return this.get('store').findRecord('photo', params.photo_id);
}
});
// photos.js
export default Ember.Route.extend({
setupController(controller, model) {
let photos = this.get('store').findAll('photo');
console.log('add all...');
// convert to an array so I can modify it later
photos.then(()=> {
controller.set('photos', photos.toArray());
});
},
});
I can always call the findAll() function regardless where the user goes, but I don't think this is smart.
The way I am dealing with the page transitions:
To go to photos I use:
{{#link-to 'photos'}}All{{/link-to}}
To go to /photo/ID I inject the service '-routing' and I use in one event click like this:
routing: Ember.inject.service('-routing'),
actions() {
selectRow(row) {
this.get("routing").transitionTo('photo', [row.get('id')]);
}
}
findAll will get it from a store and return immediately and later on it will request the server and update the store. but in your case, as you are not using route model hook, so this live array will not be updated so it will not reflect it in the template.
If I visit firstly the route /photo/ID and then go to /photos, it will
only show one object on the latter.
In the above case, store will contain only one reocrd, so when you ask for store data using findAll it will return the existing single record.
Another option is,
avoiding this photos.toArray() - It will break live-array update, I am not sure why do you need it here. since photos is DS.RecordArray.
Note: It's important to note that DS.RecordArray is not a JavaScript
array, it's an object that implements Ember.Enumerable. This is
important because, for example, if you want to retrieve records by
index, the [] notation will not work--you'll have to use
objectAt(index) instead.

Ember - Automatically redirect to firstObject

I'd like an Ember path /clinic/1 to automatically redirect to show the first doctor: /clinic/1/doctor/1.
Each clinic has many doctors.
Unfortunately if I use this code:
var doctor = clinicController.get('content.doctors.firstObject');
router.transitionTo('clinic.doctor.index', doctor);
... it does not work, as content.doctors.length is still 0 when this code runs in app_router.js.
Any ideas?
You should be able to do this:
App.DoctorsRoute = Ember.Route.extend({
model: function() {
return App.Doctor.find();
},
redirect: function() {
var doctor = this.modelFor('doctors').get('firstObject');
this.transitionToRoute('doctor', doctor);
}
});
This will work because:
If the model hook returns an object that hasn't loaded yet, the rest of the hooks won't run until the model is fully loaded.
If the redirect hook transitions to another route, the rest of the hooks won't run.
Note that as of 2426cb9, you can leave off the implicit .index when transitioning.
Redirecting on the Route doesn't work for me in my ember-data based app as the data isn't loaded at the point of redirection, but this does work for me...
In the roles controller I transition to the role route for the firstObject loaded.
Application.RolesController = Ember.ArrayController.extend({
selectFirstObject: function () {
if (this.get('content').get('isLoaded')) {
var role = this.get('firstObject');
this.transitionToRoute('role', role);
}
}.observes('content.isLoaded')
});
HTH, gerry
As an update, if you don't want to redirect because you have a nested route, you'll want to use conditional redirect based on the intended route.
redirect has two arguments passed to it, the model and the transition object. The transition has the property targetName where you can conditionally redirect based on its value.
redirect: function(model, transition){
if(transition.targetName ==='doctors.index'){
this.transitionTo('doctor', model.get('firstObject'));
}
}
For EmberCLI users, you'd achieve the same by doing the following:
//app/routes/clinics/show.js
import Ember from 'ember';
export default Ember.Route.extend({
redirect: function(model) {
var firstDoctor = model.get('doctors.firstObject');
this.transitionTo('doctor', firstDoctor);
}
});

Order of events triggerd by Backbone.Router when using navigate

I am using Backbone's "all" event to catch all route events in my app in order to log the page views. This works well as long as I don't use navigate to manually trigger a route.
In the following example, I forward the user from the dashboard route to the login route. Backbone fires the event AFTER the route callback is executed, leading to the following output:
showDashboard
showLogin
route:showLogin
tracking:/login
route:showDashboard
tracking:/login
Obviously this is not what I want. I know I could call showLogin instead of using navigate to trigger the login route and this is what I am doing right now, but I would like to know why the order of the events is not the same than the order of the triggered callbacks.
Here is my router (shortened):
var AppRouter = Backbone.Router.extend({
routes: {
"/login": "showLogin",
"": "showDashboard",
},
initialize: function() {
return this.on('all', this.trackPageview);
},
trackPageview: function(eventName) {
console.log(eventName);
var url = Backbone.history.getFragment();
console.log('tracking: ' + url);
},
showDashboard: function() {
console.log('showDashboard');
// check if the user is logged in etc.
this.navigate('#/login', { trigger: true });
},
showLogin: function() {
console.log('showLogin');
}
});
Backbone's Router is actually very simple, and if you read the code you'll see the following in it's constructor:
this._bindRoutes();
this.initialize.apply(this, arguments);
_bindRoutes attaches all your routes as you expect, and it does this before your initialize function gets called. So your binding will always fire after Backbone's does.
You're probably going to be better off finding another way to do this.
You could call a before type function yourself in your routes to do stuff like track pageviews/etc. Or maybe you could just override route, track your pageview and then make sure to call Backbone's implementation with something like Backbone.Router.prototype.route.call(arguments);

Backbone.js how do i define a custom set of routes depending on a certain application state

Currently building an app that runs on mobile phones
not related to the issue at hand, but through a certain event
the app lands in a state, either online or offline (internet available on the phone or not)
the offline app is very limited, only a few screens available)
now stop me if you catch me doing something stupid or something that i could to a lot better,
but my first thought was to have the Router have a dynamic set of routes,
much like you can define a dynamic url property on a collection.
so instead of this:
var router = Backbone.Router.extend({
routes: {
'' : 'homeAction',
'categories' : 'categoriesAction',
...
},
homeAction: function(){ },
categoriesAction: function(){ }
});
i was thinking of this:
var router = Backbone.Router.extend({
initialize: function(){
this.on('app:togglestate', this.toggleRoutes, this);
},
toggleRoutes: function () {
var router = this;
if(App.onlineModus)
router.routes = { /* hash with online routes here */ };
else
router.routes = { /* hash with offline routes here */ };
},
routes: {
'' : 'homeAction',
'categories' : 'categoriesAction',
...
},
homeAction: function(){ },
categoriesAction: function(){ }
});
though that aparently breaks the whole app,
as the Backbone.history.start(); throws an error, cannot call function start from undefined.
leading me to believe i the routes object is somehow used upon initialization and cannot be changed on the fly.
am i possibly thinking to far?
should i achieve this some other way?
other idea's i had were:
having the routes exactly like url, where the routes argument is a function returning a hash, that didn't work either
and now i'm thinking totally differnt, something along the lines of testing if the app is in online or offline modus in every route's Action. though that seems too mutch i'd probably have to relay them all through a single Action, which only passes to the actual action if the route is accessible in offline modus? but i would not really have a clear idea on how to start with such a relay action without writing too mutch boilerplate code...
In order to dynamically update the routes you will need to make a call to _bindRoutes() after updating the routes.
For example:
toggleRoutes: function () {
var router = this;
if(App.onlineModus)
router.routes = { /* hash with online routes here */ };
else
router.routes = { /* hash with offline routes here */ };
// Get rid of previous navigation history
if(Backbone.history){
Backbone.history == null;
}
// Bind the new routes
router._bindRoutes();
}
Note that when you dynamically change the routes the history is no longer valid so you need to delete the previous history. When _bindRoutes is called it automatically instantiates a new Backbone.history when is called this.route.
I had to do something very similar. I don't have the code in front of me, but this should be right around what I did: (Edit: fleshed it out a bit so you can actually run it now)
ApplicationRouter = Backbone.Router.extend({
//some stuff
constructor: function (routes) {
this.routes = routes;
Backbone.Router.prototype.constructor.call(this);
}
});
routeObject = {
"help": "help"
}
ApplicationRouter.instance = function(routes) {
if (!this._instance) {
this._instance = new ApplicationRouter(routes);
}
return this._instance;
}
ApplicationRouter.instance(routeObject);
ApplicationRouter.instance().on('route:help', function() {
console.log('helped');
});
Backbone.history.start();
//now go to page#help - the console will say "helped"
From then on out, I just referenced ApplicationRouter.instance() when I needed access to the application router.

Categories