jquery code organization
Her开发者_C百科e is the scenario:
I am developing a web application written in servlet JSP.
Basically the controller looks at the action, invokes correct model class which dispatches to a particular JSP.
So for each distinct view there is a JPS. And there are many different UI views. (user's dashboard, discussion forums, a particular thread in a discussion forum, inbox for PMs etc etc)
I am using jQuery and the way I have organized my code is as follows:
rootdir
|______ jsp
|_______ javescript
jsp directory has all the jsp file. For each jsp file there is a corresponding javascript file which holds my jQuery stuff ($.ready() ... and everything related to that page). And every jsp file has a refermnce to that javascript file.
Now I have 50 jsp files, and hence 50 .js files.
Is there a better way to organize my javascript files.
--Jatin
I usually build my javascript with general purpose uses in mind. For example, all navigation links that require javascript can more than likely be handled using a single .live() event that performs actions based on what the href of the link is or whatever data attributes are present.
When it comes to jquery ui widgets such as datepicker and autocomplete, those can be defined globally using .live() aswell. If they need additional options, place them in a data attribute.
<input type="text" class="autocomplete" name="someautompletename"
data-options="{source: ['jQuery','Coldfusion','Railo','JavaScript']}" />
...
$(".autocomplete:not(.live)").live("click",function(e){
var data = $(this).data("options");
$(this).autocomplete(data ? data : {}).addClass('live').focus();
});
You could also build form handling to work the same way. By building your scripts this way, you can end up with a single js file that handles 90% of those jsp pages, while including additional files on the pages that need a little more(such as dialogs).
精彩评论