jquery in ajax loaded content

Posted by Kim Gysen on Stack Overflow See other posts from Stack Overflow or by Kim Gysen
Published on 2013-11-05T15:50:32Z Indexed on 2013/11/05 15:53 UTC
Read the original article Hit count: 191

Filed under:
|

My application is supposed to be a single page application and I have the following code that works fine:

home.php:

<div id="container">
</div>

accordion.php:

    //Click functions: load content 
    $('#parents').click(function(){
        //Load parent in container
        $('#container').load('http://www.blabla.com/entities/parents/parents.php');
    }); 

parents.php:

<div class="entity_wrapper">
    Some divs and selectors 
</div>
<script type="text/javascript">
    $(document).ready(function(){
        //Some jQuery / javascript 
    }); 
</script>

So the content loads fine, while the scripts dynamically loaded execute fine as well.
I apply this system repetitively and it continues to work smoothly.
I've seen that there are a lot of frameworks available on SPA's (such as backbone.js) but I don't understand why I need them if this works fine.

From the backbone.js website:

When working on a web application that involves a lot of JavaScript, one of the first things you learn is to stop tying your data to the DOM. It's all too easy to create JavaScript applications that end up as tangled piles of jQuery selectors and callbacks, all trying frantically to keep data in sync between the HTML UI, your JavaScript logic, and the database on your server. For rich client-side applications, a more structured approach is often helpful.

Well, I totally don't have the feeling that I'm going through the stuff they mention.
Adding the javascript per page works really well for me.
They are html containers with clear scope and the javascript is just related to that part.
More over, the front end doesn't do that much, most of the logic is managed based on Ajax calls to external PHP scripts. Sometimes the js can be a bit more extended for some functionalities, but all just loads as smooth in less than a second.

If you think that this is bad coding, please tell me why I cannot do this and more importantly, what is the alternative I should apply. At the moment, I really don't see a reason on why I would change this approach as it just works too well.

I'm kinda stuck on this question because it just worries me sick as it seems to easy to be true. Why would people go through hard times if it would be as easy as this...

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about AJAX