應用程序中jQuery表單綁定代碼的最佳實踐 (Best practices with jQuery form binding code in an application)


問題描述

在應用程序中使用 jQuery 表單綁定代碼的最佳實踐 (Best practices with jQuery form binding code in an application)

我們有一個應用程序,其中包含大量對服務器端代碼的 jQuery JSON 調用。正因為如此,我們有大量的綁定代碼來解析響應並將適當的值綁定到表單。這是一個由兩部分組成的問題。

  1. 處理大量具有不同數據的表單的推薦方法是什麼。現在正在嘗試採用結構化方法為每個頁面設置一個 js“類”,包括一個 init、wireClickEvents 等。試圖讓一切都符合要求。

  2. 在創建重複的 jQuery 代碼或任何類型的推薦結構方面是否有任何“最佳實踐”,而不僅僅是在 js 文件中拋出一堆函數?


參考解法

方法 1:

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

方法 2:

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.

方法 3:

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)
   }

(by Sean ChambersChris WestbrookJason Buntingordnungswidrig)

參考文件

  1. Best practices with jQuery form binding code in an application (CC BY‑SA 2.5/3.0/4.0)

#ooad #jquery #javascript






相關問題

接口實現是否應該獨立 (Should Interface implementations be independent)

當我們有不同的回報類型時實現策略模式 (Achieve strategy pattern when we have different return type)

抽象VS信息隱藏VS封裝 (Abstraction VS Information Hiding VS Encapsulation)

應用程序中jQuery表單綁定代碼的最佳實踐 (Best practices with jQuery form binding code in an application)

耦合與內聚 (Coupling and cohesion)

什麼時候應該在C ++中使用類與結構? (When should you use a class vs a struct in C++?)

What is an anti-pattern? (What is an anti-pattern?)

如何根據編程代碼顯示聚合? (How to Show Aggregation in terms of A Programming Code?)

協調 MVP 三元組 (Coordinating MVP triads)

裝飾器和虛擬方法 (Decorators and Virtual Methods)

設計和建築有什麼區別? (What is the difference between Design and Architecture?)

特定時間段有效的業務規則——如何有序管理 (Business rules that are valid for specific time span – how to manage in an orderly manner)







留言討論