Backbone Router confusion on howto trigger - backbone.js

I can't seem to get the Backbone Router working in an expected manner. I i) instantiate my Router, then ii) call Backbone.history.start( { pushState: true, root: '/' } ). With the code below...
1) going to "/dashboard" or "/grid", the defined functions are not called
2) when I invoke myrouter.navigate("grid"), the defined functions are not called
**) However, if I then go back or forwards throught the history, then the defined functions are called.
Router : Backbone.Router.extend
routes:
"dashboard": "dashboard"
"grid/:storyid": "grid"
dashboard: ->
console.log("...")
grid: (storyid) ->
console.log("...")
What do I need to do to get cases 1) and 2) to work?
Thanks

Your router is working exactly as it's supposed to. I think your expectations of how it works, and why, are off.
1) going to "/dashboard" or "/grid", the defined functions are not called
When you type "/dashboard" or "/grid" in to your browser's URL bar, your browser makes a request to your server to get that url. This bypasses the router because the browser is making the request back to the server.
The only time typing a URL in to the browser's URL input would not request a new page from the server, is when you are only modifying the hash fragment: "#whatever".
when I invoke myrouter.navigate("grid"), the defined functions are not called
The default behavior of router.navigate is to update the URL w/ the appropriate route, but not that route to be handled by the router - exactly what you are describing.
If you want to force the browser to process the route change, pass true as a second argument: myrouter.navigate("grid", true)
**) However, if I then go back or forwards throught the history, then the defined functions are called.
This works because the router has registered itself w/ the browsers history API and is given the opportunity to handle the URL changes that are caused by the fwd / back buttons, before the browser goes back to the server to get the requested URL.

Related

Using UI router, how to pass parameters to url without altering the state?

In my controller, I use $state.go('home', {"parameters": paramValue, "parameter1": another value, "parameters3": another another value}, {reload:true}); and while this does attempt to go to the home state and passes the parameters to the url, the home state view keeps loading. If I copy the url with the parameters passed, and click enter, everything loads properly.
This is the process of going to the home tab.
-> the url changes to reflect that home state is trying to be reached
-> a second reload occurs when the url gets the parameters passed. The parameters do get passed successfully.
-> It keeps trying to load the home view.
The url is correct and works( parameters and all); as I can copy the link and access it. I've also toggled with reload to false.
Should I try transitionTo?
Hey all for anyone else having a similar kind of problem. The answer to stop the unneccessary reloading is to add the notify:false to state.go('main.home', params, {notify:false});

React-redux get site base URL / window.location

Hopefully this is a very simple question:
I want to create a string containing the full URL to a page on my site, like:
https://example.com/documents/1
Ideally I'd like to generate this in a react-redux connect()-ed container, in mapStateToProps(). Where the page is a grandchild of a react-router Route using browserHistory (so maybe I can get it from react-router or browserHistory somehow?) If necessary I'd do it in a full-on React class.
But I can't for the life of me find out how to do this. window (as in window.location) is always undefined in mapStateToProps() (no big surprise there) and in my view components' render() function.
So far I have only found ways to access the current route, e.g. "/documents/1", which is only a relative path and does not contain the site base url (https://example.com/)
So firstly, remember your code runs on client and server so any access to window needs to be wrapped in a check.
if (typeof window !== 'undefined') {
var path = location.protocol + '//' + location.host + '/someting'; // (or whatever)
} else {
// work out what you want to do server-side...
}
If the URL you generate shows in the DOM, and on the client you populate the store with this URL before the first render, you're going to get a checksum error. If you really want to avoid the error you can wait until componentDidMount() in your root component to get/set the url.
After componentDidMount you can have direct access to the origin location so that you can get the root url.
I use the below code in my JSX all the time so that i dont have to worry about the root path ex: dev env this would be localhost:3000/whatever, staging this will be AppStaging.heroku/whatever/..... and in production it would evaluate to www.myapp.com/whatever
`${window.location.origin.toString()}/whateverRoute/`
You Can try!!
window.location.origin
you can try the URL API. Take a look at this link for more details https://developer.mozilla.org/en-US/docs/Web/API/URL
const url = new URL("blob:https://mozilla.org:443/")
console.log(url.origin);
// Logs 'https://mozilla.org'

Automatic Deep Sub-Route Redirecting in React-Router

I have recently been transitioning a project from AngularJS + UI-Router+ UI-Router-Extras to React + React-Router.
One of the better features in UI-Router-Extras that I'd like to bring to React-Router is called
Deep State Redirect. In this feature, when navigating to a route which has subroutes, the application knows to redirect the user to the last subroute of it that was visited, or if none of its subroutes have yet been visited then it redirects to its first subroute to have been registered.
So for example if the loaded routing tree looks like this:
/main
|_/main_sub_1
|_/main_sub_2
/secondary
and the user starts at route /main/main_sub_2, then goes to /secondary, then goes to /main, they will be automatically redirected to /main/main_sub_2 since /main/main_sub_2 is the last subroute of /main to have been visited.
I know that I could implement this in react router by using
<IndexRedirect to={getLastSubRoute(parentRoute)}> where parentRoute is the full path of the parent <Route> tag, and getLastSubRoute is self-explanitory, but the problem with this is that I would need to add such an <IndexRedirect> tag to every single route I create, which is not optimal since the routes are loaded dynamically, there may be up to 100 subroutes, and much of the application's routing will be written by other people who I shouldn't be relying on to remember to add that tag under every <Route> tag they write.
Ideally, I should be able to apply some function or mixin to the base <Router> tag in the React routing definition to add this functionality to all routing underneath it, but I'm not sure where to start. How might I solve this problem?
Your best bet and possibly the simplest solution would be to set an onChange hook on one of the top level routes. The hook would get called with the next parameter, which would be the next route that the user would be going to.
You would also have the hierarchical structure of routes there (navigating through to parent and children of the parent), so you could dynamically redirect using the replace function, that gets passed in as a parameter also.
I implemented something similar for permission and role management. What I also did was to .bind my store to the function that I pass into the route hook. You could possibly store the route you'd like to redirect to on the user in the state tree. Basically what you refer to as getLastSubRoute.
...
<Route onChange={myRedirectFunctionThatHasStoreBound} .. >
... // other routes
</Route>
...
function myRedirectFunctionThatHasStoreBound(store, prev, next, replace, callback) {
const user = store.getState().user;
const redirectTo = getLastSubRouteForRoute(user, next);
if (redirectTo) {
replace(redirectTo);
}
// don't forget this is you list callback as a param
// your app might stop working, explanation below
callback();
}
If callback is listed as a 4th argument, this hook will run asynchronously, and the transition will block until callback is called.
EDIT: Keep in mind that this will only work if you are using react-router that's newer than or equal to in version to react-router 2.1

Prevent deep link in react-router

In my application I'd like to have certain portions of the app not be able to deep linked to. For example our users have a list of surveys and I'd like if someone tried to go directly to a particular survey directly such as /survey/1 that react router would pick up on this and immediately redirect them back to /survey and they would have to select the one they want. I've tried to write onEnter hooks but they seem to be very cumbersome since the only way I've been able to get them to behave correctly is to store some global state that says they have been to the main page and inspect that every time the route is navigated to.
Im using pushstate in my application if that makes any difference and react-router 2.0
I'd like to try to avoid having to write server rewrite rules for this since there are a lot of areas in my application where this rule is applicable.
I have a suggestion which is similar to the onEnter hook:
Wrap the component of the survey/:id route with a function which verifies if deep linking is allowed or not, let's call this function preventDeepLinking
The preventDeepLinking function checks if the location state contains a certain flag, let's say allowDeep. This flag would be set in the location state when navigating from another page of your app. Obviously, this flag will not be set when the user tries to navigate directly to the page of a survey.
The preventDeepLinking function will render the wrapped component only if deep linking is allowed, otherwise will redirect to a higher route.
I created a sample on codepen.io. You can play with it in the debug view of the Pen: http://s.codepen.io/alexchiri/debug/GZoRze.
In the debug view, click the Users link and then on a specific user from the list. Its name will be displayed below. Notice that its id is part of the url. Remove the hash including the ?_ and hit Enter. You will be redirected to /users.
The code of the Pen is here: http://codepen.io/alexchiri/pen/GZoRze
The preventDeepLinking function can be improved, but this is just to prove a point. Also, I would use the browserHistory in react-router but for some reason I couldn't get it running in codepen.
Hope this helps.

Converting existing web app to use hashtag URIs using Backbone.js

I'm attempting to use Backbone and it's Router to turn an app into an ajax app, however it currently uses several different methods (helpers) of generating links. Unfortunately, this means manually changing each and every link to use a hashtag is out of the question.
What would be the best method of ensuring every link, form post, redirect, etc. gets parsed as a hashtag URL that can be caught by Backbone's Router? Or, even better, is it possible for the Router to accept "true URL's" from a request? Example: a request to /app/mail/inbox.php is caught by a rule in the Router, and is turned into #/mail/inbox after firing the appropriate method to handle the request.
What would be the best method of ensuring every link, form post, redirect, etc. gets parsed as a hashtag URL that can be caught by Backbone's Router?
I don't think that Backbone.Router is supposed to handle, say, form posts. It's supposed to give your application view state—bookmark-friendly and refreshable URLs [1].
If you want to ‘ajaxify’ forms, then you probably should add a handler for form's submit event and do something like $.ajax() there, preventing the default action.
Regarding plain old links, History.pushState() support has been added to Backbone recently. It means that you can define your routes as /app/*, and don't need to replace old href attributes. However, you'll still need to catch link click events to prevent default action.
For example:
var handle_link_click = function(e) {
path = $(e.target).attr('href');
app.main_router.navigate(path, true); // This.
e.preventDefault();
};
$('a:internal').click(handle_link_click);
Router's navigate() method will do history.pushState() if it's available, falling back to old hashchange. And true as a second argument means that it will fire corresponding handler action.
[1] See also this presentation about Backbone

Resources