jay
jay

Reputation: 12495

Backbone/jQuery event for when the client tries to go forward/go back?

I'm building a backbone app and am learning about how to use Backbone's pushState. My app's main view is a 'Feed' view, which displays a bunch of items. When you click on an item, it loads a new item 'Show' view, and slips it into the page.

Right now, I've successfully got my app using pushState true to enter in the browser's history a record for each article viewed.

However, when I go 'back' in my browser's history, I'd like to trigger an event to do some stuff on the show view. Is there a backbone or jQuery event/function that I can use to detect when the user has selected to go forward/back in history?

It would be great to use an backbone event like:

 events: {
  'dblclick':'test'
 },

Upvotes: 1

Views: 818

Answers (1)

Bryan Clark
Bryan Clark

Reputation: 2602

If you're using a view for an App controller you can use this trick of passing the window object as your el option to the View. With the window object held in the View you'll get all the window events bound to your events hash such that you could add an event like popstate to your hash and you'll get a back button event.

I quickly tested this so it should work for you:

var App = Backbone.View.extend({
    events: {
      "popstate":          "onPopState"
    },
    onPopState : function onPopState() {
        console.log("onPopState");
    }
});
var MainApp = new App({ el : window });

Upvotes: 3

Related Questions