Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selective history.back() using Backbone.js

I have a Backbone app. I'm using Backbone.history to enable use of the back button. We have a page (settings) that auto loads a popup requiring input from the user. If the user chooses cancel, I want to go back to the previous page. I can do this using window.history.back().

The problem is, if the user went directly to that page (app#settings) from another url (like google) by typing the url into the browser, I want to redirect the user to the home page (app/) rather than going back to google.

I haven't been able to figure out any way to do this. Backbone.history looks like it store information from the browser's back button, so it has a history even if they just arrived at the app. I also couldn't find a way to view the previous url.

Is this possible?

like image 881
FrizbeeFanatic14 Avatar asked Feb 13 '13 18:02

FrizbeeFanatic14


People also ask

What is the only method available in the backbone JS history?

There is only method named "start" can be used to manipulate the Backbone. js history.

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Is Backbone JS frontend or backend?

Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.

What is backbone JS used for?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.


1 Answers

Wrap the back navigation logic in a method of your own. Perhaps on the router:

var AppRouter = Backbone.Router.extend({

  initialize: function() {
    this.routesHit = 0;
    //keep count of number of routes handled by your application
    Backbone.history.on('route', function() { this.routesHit++; }, this);
  },

  back: function() {
    if(this.routesHit > 1) {
      //more than one route hit -> user did not land to current page directly
      window.history.back();
    } else {
      //otherwise go to the home page. Use replaceState if available so
      //the navigation doesn't create an extra history entry
      this.navigate('app/', {trigger:true, replace:true});
    }
  }
});

And use the router method to navigate back:

appRouter.back();
like image 129
jevakallio Avatar answered Sep 24 '22 01:09

jevakallio