Best practices with jQuery form binding code in an application

Question!

We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question.

  1. What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed.

  2. Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file?



Answers

You should probably look into a framework like knockout.js This way you can just update your models and the forms will update automatically.



I think there are multiple challanges for you. The first question is how to structure javascript code, i.e. how to build namespaces so that you don't fight name clashes or have to name your functions like

form1validate
form1aftersubmit
form2validate
form2aftersubmit

One of the proven patterns for modules in javascript is to use an anonymous function to build a new naming scope. The basic idea is shon in the following code

(function() {
  var foo = 1;
})();

(function() {
  if(foo == 1) alert("namespace separation failed!")
})();

I think this blog entry is a good introduction.

The second question you face is how to avoid all the repetition in javascript code. You have a couple of weapons against this.

  1. functions - this seams obvious but it's often forgotten to refactor common code into functions where it can be done. In you case this will be functions to copy values from the json response into the forms and like that
  2. higher order function - or functions as data - or callback, as they are often called in javascript. These are the mightiest weapon in javascript. In case for form and ajax handling you can use callback to avoid repetition in the control flow of your forms.

Let me construct an example out of my head (using jquery for convinence)

// this is a validator for one form
   var form1validator = function() {
     if($("input[name=name]",this).attr("value").length < 1 &&
        $("input[name=organisation]",this).attr("value").length < 1)
       return "Either name or organisation required" 
   }

   // and this for a second form
   var form2validator = function() {
     if($("input[name=age]",this).attr("value").length < 21
       return "Age of 21 required"
   }

   // and a function to display a validation result
   var displayResult = function(r) {
     $(this).prepend("<span></span>").text(r);
   }

   // we use them as higher order functions like that

   $("#form1").onSubmit(validator(form1validator, displayResult, function() {
     //on submit
     ...send some xhr request or like that
   });

   $("#form2").onSubmit(validator(form2validator, displayResult, function() {
     this.submit() // simply submit form
   });

   $("#form1b").onSubmit(validator(form1validator, function(r) {
     alert("There was an validation error " + r);
   }, function() {
     //on submit
     ...send some xhr request or like that
   });


   // the validator function itself would be defined as

   function validator(formValidator, displayResult, onSubmit) {
     var r = formValidator.apply(this)
     if(typeof(r) === 'undefined')
       onSubmit(this)
     else
       displayResult(r)
   }


Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data.

I don't know what more there is to say - writing UI code for the browser in JavaScript is no different than writing UI code for other types of apps, as far as I am concerned. Build classes and instantiate them as needed, populate them with data, have them throw events, etc. etc.

Am I up in the night on this? :)


EDIT: In other words, yes - do what you are doing, for the most part. I see too many novice JavaScript hackers write a bunch of poorly-cohesive functions that don't appear to be a part of anything specific other than they are all in a single file. Hope that makes sense.



This video can help you solving your question :)
By: admin