Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone and jqm: back button how to restore page context

I'm building an HTML5 mobile application using Backbone, require and jQuery mobile as a technology stack. The application is really smoothy with a connection to a backend web service and so on. To Change between the pages I use jQuery changePage. To instanciate Backbone views I use the following strategy:

$( document ).delegate("#card-delivery-address", "pageshow", function(){
    require(["js/views/cardDeliveryAddressViews.js" ], function(cardDeliveryAddressViews) {
        new cardDeliveryAddressViews();
    });
});
  1. $.mobile.changePage('deliveryAddress.html') => changes the current page using jquery mobile

  2. When an event called "pageshow" is fired on #card-delivery-address (which means that my page was inserted in the DOM and successfully rendered) => create the backbone view and bind the $el to an existing DOM and taking control on the DOM events using backbone views.

  3. To pass data and instances between views we use a window.tempData global variable in which we put the context data so that the new view will know what to do.

Doing one way navigation is successful, suppose that I come from view1 --> view2 (with tempData) then from view2 --> view 3 (override the same tempData). Now, and here is my problem: if we want to go back from view 3 --> view 2 we will need the tmpData content that we used to initialize and render the view 2. The same thing when we want to go back to view1.

Note: I'm not using backbone router but I can change to use it if that will solve my problem.

Any ideas guys?

like image 770
Houcem Berrayana Avatar asked Mar 23 '23 03:03

Houcem Berrayana


1 Answers

Ok let's give it another try. We'll implement a data store keyed by pages' path.

var pagesData = {};

// Let's assume we just switched to page '/my/page/1'

// Get a reference to the stored page data if it exists, 
// or create it empty and return it.
var currentPageData = pagesData[window.location.pathname] ||  
                     (pagesData[window.location.pathname] = {});

currentPageData.foo = 'bar';

console.log(pagesData['/my/page/1'].foo); // > "bar"

Now all your pages have a "local" datastore that allows them to save their state/data throughout navigation.

NB: If you don't use pushState, you have to use window.location.hash in place of window.location.pathname as a key in PagesData.

like image 125
thibauts Avatar answered Apr 25 '23 16:04

thibauts