AJAX driven "page complete" function? Am I doing it right?
Posted
by
Julian H. Lam
on Programmers
See other posts from Programmers
or by Julian H. Lam
Published on 2011-10-14T13:55:42Z
Indexed on
2011/11/13
18:05 UTC
Read the original article
Hit count: 302
JavaScript
|mootools
This one might get me slaughtered, since I'm pretty sure it's bad coding practice, so here goes:
I have an AJAX driven site which loads both content and javascript in one go using Mootools' Request.HTML
.
Since I have initialization scripts that need to be run to finish "setting up" the template, I include those in a function called pageComplete()
, on every page
Visiting one page to another causes the previous pageComplete()
function to no longer apply, since a new one is defined.
The javascript function that loads pages dynamically calls pageComplete()
blindly when the AJAX call is completed and is loaded onto the page:
function loadPage(page, params) {
// page is a string, params is a javascript object
if (pageRequest && pageRequest.isRunning) pageRequest.cancel();
pageRequest = new Request.HTML({
url: '<?=APPLICATION_LINK?>' + page,
evalScripts: true,
onSuccess: function(tree, elements, html) {
// Empty previous content and insert new content
$('content').empty();
$('content').innerHTML = html;
pageComplete();
pageRequest = null;
}
}).send('params='+JSON.encode(params));
}
So yes, if pageComplete()
is not defined in one the pages, the old pageComplete()
is called, which could potentially be disastrous, but as of now, every single page has pageComplete()
defined, even if it is empty.
Good idea, bad idea?
© Programmers or respective owner