I've been struggling lately with understanding the best way to organize jQuery code. I asked another question earlier and I don't think I was specific enough (found in this question here).
My problem is that the richer you make an application, the quicker your client side gets out of control. Consider this situation...
//Let's start some jQuery $(function() { var container = $("#inputContainer"); //Okay let's list text fields that can be updated for(var i=0; i < 5; i++) { //okay let's add an event for when a field changes $("<input/>").change(function() { //okay something changed, let's update the server $.ajax({ success:function(data) { //Okay - no problem from the server... let's update //the bindings on our input fields $.each(container.children(), function(j,w) { //YIKES!! We're deep in here now!! $(w).unbind().change(function() { //Then insanity starts... }); // end some function }); //end some loop } // what was this again? }); //ending something... not sure anymore }).appendTo(container); //input added to the page... logic WAY split apart }; //the first loop - whew! almost out! }); //The start of the code!!
Now this situation isn't too far from impossible. I'm not saying this is the right way to do it, but it's not uncommon to find yourself several levels down into a jQuery command and starting to wonder how much more logic can add before the screen begins to melt.
My question is how are people managing this or organizing to limit the complexity of their code?
I listed how I'm doing it in my other post...
Just want to add to what was mentioned previously that this:
$.each(container.children(), function(j,w) { $(w).unbind().change(function() { ... }); });
can be optimized to:
container.children().unbind().change(function() { ... });
It's all about chaining, a great way to simplify your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With