Backbone.js changes URL without reloading page

I have a website that has a user page. There are several links on this page that allow you to explore your user profile. I would like to make sure that when one of these links is clicked, the URL changes, but the upper third of the page containing the custom banner does not reload.

I am using Backbone.js

I feel like I'm in one of those situations where I have such a poor understanding of the problem I'm dealing with, I ask the wrong question, so please let me know if this seems like a case

+7
pushstate
source share
2 answers

My mistake was that a special built-in method was built into the main system. Not.

Just do the following line of code

window.history.pushState('object or string', 'Title', '/new-url'); 

will change the URL of your browser without reloading the page. You can open the javascript console in your browser right now and try it on this page. This article explains how this works in more detail (as noted in this SO page ).

Now I have associated the following event with the document object (I am launching the site on one page):

 bindEvents: () -> $(document).on('click', 'a', @pushstateClick) pushstateClick: (e) -> href = e.target.href || $(e.target).parents('a')[0].href if MyApp.isOutsideLink(href) == false if e.metaKey #don't do anything if the user is holding down ctrl or cmd; #let the link open up in a new tab else e.preventDefault() window.history.pushState('', '', href); Backbone.history.checkUrl() 

See this post for more details.

Note that you can pass the pushstate: true option to your call to Backbone.history.start (), but it just makes it so that going directly to a specific page (e.g. example.com/exampleuser/followers) will call and not just nowhere.

+10
source share

Routers are your friend in this situation. Basically, create a router that has several different routes. Your routes will cause different views. These views will simply affect the part of the page that you define. I'm not sure if this video will help, but it may give you some idea of ​​how routers interact with the page: http://www.youtube.com/watch?v=T4iPnh-qago

Here is an example:

 myapp.Router = Backbone.Router.extend({ routes: { 'link1': 'dosomething1', 'link2': 'dosomething2', 'link3': 'dosomething3' }, dosomething1: function() { new myapp.MyView(); }, dosomething2: function() { new myapp.MyView2(); }, dosomething3: function() { new myapp.MyView3(); } }); 

Then your URL will look like this: www.mydomain.com/#link1.

Also, since the <a href=''></a> tags will automatically trigger a page refresh, make sure you call .preventDefault (); on them if you do not want the page to refresh.

+1
source share

All Articles