jeudi 12 mars 2015

preventing late ajax response from updating div

Assume the following structure for a primitive single page app:



<nav>
<a href="/static">static</a>
<a href="/ajax">ajax</a>
</nav>

<h1 id="title"></h1>
<div id="content"></div>


clicking on the first link quickly sets some static content:



$('#title').html('static title');
$('#content').html('static content');


clicking on the second link fetches some content from a server and when this is done, uses it to set the content on the page:



$('#title').html('ajax title');
$.get(
url,
data,
function success(data) {
$('#content').html(data);
}
);


Clicking on the ajax link and then quickly (before ajax returns) to the static link is problematic because when the ajax returns it'll replace the content even though the user has "switched" to the static page, so I get an inconsistent app state with title from one page and content from another:



<h1>static title</h1>
<div>dynamic content from ajax</div>


What is the best way to sort this out?


I've thought of:



  1. using a global (or an application scoped) variable where I'll be tracking which page is currently visible, so when ajax responses return I should be checking that variable before writing content on screen.

  2. have an ajax queue or something and call abort on all possible pending ajax responses whenever I'm switching pages.

  3. not sharing the same div#content for all pages. Each page get's its own content and switching pages also involves showing/hiding divs.


Is there a better way?


Aucun commentaire:

Enregistrer un commentaire