Jason Hoffmann
Jason Hoffmann

Reputation: 815

Organizing jQuery AJAX without MV* Framework

I am in the process of building a static site that requires smooth page transitions between pages. These pages are going to be AJAX loaded in when any link is clicked on to allow things to keep smooth and prevent page reloads.

Seeing as how all of the content is static HTML (compiled locally with Grunt), I don't see the need for an MV* framework like Backbone or Angular. That would probably be overkill as I'm not really working with data in any meaningful way. All I really need is the AJAX section of the jQuery library.

My question is, does anybody know of a framework that deals with just organizing AJAX calls in jQuery without further complexity? Or are there any tips out there for organizing these calls, because I can see that they are going to get messy quick.

Upvotes: 2

Views: 306

Answers (1)

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

How about creating an object with all the static pages ( views ) and the relevant href anchors, like say :

var views = [

   { view: '/about.html',href:'#about'},
   { view: '/contact.html', href'#contact'}

];

So in the html

<a href="#contact">Contact</a> |
<a href="#about">About</a>

<div id="viewStage"></div>

with some jquery and a function to watch for the hash change in the address bar and hook it up to the view that is defined for it.:

(function() {

   var $viewStage = $('#viewStage');

   function loadView(view) {

     $viewStage.html('<div class="loading"></div>').load(view);

   }

   /* matches the hash url to the view in the 'views' array of objects */
   function getView(hash) {
      for (var i=0, i < views.length; i++) {
         if (views[i].href === hash) { return views[i].view; break; }
      }    
   }

    /* listen for the anchor hashtag change */
    $(window).on('hashchange', function() {

       loadView(getView(document.location.hash));

     });

})();

I didn't address creating the page transition effects between loading, other than , hopefully you can see that in the loadView() we would have the opportunity to do something BEFORE you clear the html in the #viewStage div and load with new content.


That's the start of something I hope ( an MVC without the M and a debatable C ) short and friendly - as it reacts to the hash in the address bar.


EDIT: there is a jquery hash change listener abstraction to make use of here - so added that.

Upvotes: 3

Related Questions