Organize JavaScript and jQuery events – DOM-ready execution

In complex websites javascript and jquery events can conflict with each other, especially if you are using the same javascript files for different website pages.
There are many techniques to solve this issue, and I found a good solution by following these articles:
Automate firing of onload events
Markup-based unobtrusive comprehensive DOM-ready execution
Extending Paul Irish’s comprehensive DOM-ready execution

But while using this technique I faced an issue, I wanted to call more than one init function on the same page load, for example if I have my page as sections: header, login popup, inner form, footer. And each section needs to have its own init functions which load automatically when this section DOM-ready.

In Extending Paul Irish’s comprehensive DOM-ready execution article
He used the body element to run the selected action in the selected controller

And since body element is always one in any page, so we can’t call more than one controller action.

I extended this technique to use any html element in the page, something like that:

Like that i can use this element multiple times in the page for different controllers and actions.
But this required to edit JASON GARBER javascript UTIL function to fit this change.
Using the body element code was:

And using my way it required changing the code to be:

And as you see in my code I loop on all elements which use class ‘initializer’ and read/call from them one by one controllers – actions.

By applying this edit, you will be able to assign multiple different controllers in the same page based on the page sections.

 

Download Demo

Avoid sending Ajax request parameters in query string style

While reviewing some code, I found someone calling jQuery Ajax like this:

$.ajax({
       type: “POST”,
       url: “/AddPost”,
       data:  “postText=”+ PostText ,
       dataType: “json”,
       success: function (status) {

       }
}); //$.ajax({

And as you see in the previous code, it is sending the data using this line: data: “postText=”+ PostText ,

This is like a query string style, this will work well but image the user inserted a special char in PostText, such as ?? you will get on the server un expected value “”jQuery15107041011152323335_1309357585354″”

So never use this style while dealing with Ajax calls, you need to post it in JSON style like this:

$.ajax({
        type: “POST”,
        url: “/AddPost”,
        data: { postText: PostText },
        dataType: “json”,
        success: function (status) {

        }
}); //$.ajax({

This will work whatever char the user will insert.