How do you create bigger logical wholes in JS/jQuery (instead of putting everything into document.ready)?
I currently simply have everything inside document.ready, which isn't very optimal for readability and DRYness.
What are the options to create modules/classes/namespaces/function or whatever you call them in jQuery/Javascript?
For example, how would you separate these concerns:
- A general purpose function that takes an element as parameter and appends the given string into it's name attribute?
- Code that prettifies the UI (applies button effects, styling, forms, tabs, e开发者_如何转开发tc.)?
- Code that handles AJAX
Apparently, what I want to know is: How do you structure code in JS? (Thanks Alex!)
var myApp = {
init: function () { },
widget: {
init: function () { },
add: function () { },
del: function () { },
read: function () { },
edit: function () { }
},
utils: {
ui: {
rotate: function () { },
jump: function () { }
}
}
};
myApp.init();
You could create plugins.
How about just splitting your code into multiple functions which you call in document.ready? You could also group these into objects, or use one of the OO approaches such as JS.Class. I don't think this has much to do with jQuery, by the way, it's just general code structuring.
Or jQuery Ui Widgets, which goes one step further
Create plugin:
(function($){
$.fn.myCustomPlugin = function() {
// My code here
};
})(jQuery);
For javascript in general, you can just use functions/objects, see this.
For jquery, as mentioned above to create a plugin by both komar and darin...
jQuerj is very useful for dom management and for simple xhr. But if you want to create some big application I suggest to change javascript library to adopt some more "enterprise" library like dojotoolkit or yui.
精彩评论