应用程序中 jQuery 表单绑定代码的最佳实践

发布于 2024-07-04 17:16:57 字数 299 浏览 5 评论 0 原文

我们有一个应用程序,其中包含大量对服务器端代码的 jQuery JSON 调用。 因此,我们有大量的绑定代码来解析响应并将适当的值绑定到表单。 这是一个由两部分组成的问题。

  1. 处理大量具有不同数据的表单的推荐方法是什么。 现在我们正在尝试采用结构化方法为每个页面设置一个 js“类”,​​其中包含 init、wireClickEvents 等,以尝试使所有内容都一致。

  2. 除了在 js 文件中添加一堆函数之外,是否有创建重复 jQuery 代码或任何类型的推荐结构的“最佳实践”?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

Oo萌小芽oO 2024-07-11 17:16:57

您可能应该研究像 knockout.js 这样的框架,这样您只需更新模型,表单就会自动更新。

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

我不咬妳我踢妳 2024-07-11 17:16:57

不是 100% 确定您所要求的示例,但就我个人而言,我使用 MochiKit,为每个重要的客户端 UI 结构创建 JavaScript“类”(或小部件,如果您愿意)。 当然,它们知道如何用数据填充自己。

我不知道还有什么可说的——就我而言,用 JavaScript 为浏览器编写 UI 代码与为其他类型的应用程序编写 UI 代码没有什么不同。 构建类并根据需要实例化它们,用数据填充它们,让它们抛出事件等等。

我是否为此彻夜未眠? :)


编辑:换句话说,是的 - 大多数情况下,做你正在做的事情。 我看到太多的 JavaScript 新手编写了一堆内聚性很差的函数,这些函数似乎不是任何特定内容的一部分,除了它们都在一个文件中之外。 希望这是有道理的。

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.

好菇凉咱不稀罕他 2024-07-11 17:16:57

我认为您面临多种挑战。 第一个问题是如何构建 javascript 代码,即如何构建名称空间,这样您就不会遇到名称冲突或必须像这样命名您的函数。javascript

form1validate
form1aftersubmit
form2validate
form2aftersubmit

中模块的经过验证的模式之一是使用匿名函数来构建新的函数。命名范围。 基本思想在以下代码中

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

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

我认为这个 博客条目< /a> 是一个很好的介绍。

您面临的第二个问题是如何避免 javascript 代码中的所有重复。
你有几个武器来对付这个。

  1. 函数 - 这看起来很明显,但人们经常忘记将通用代码重构为可以完成的函数。 在您的情况下,这将是将值从 json 响应复制到表单中的函数,就像
  2. 高阶函数 - 或作为数据的函数 - 或回调,因为它们通常在 javascript 中调用。 这些是 javascript 中最强大的武器。 对于表单和 ajax 处理,您可以使用回调来避免表单控制流中的重复。

让我凭空构建一个示例(为了方便起见,使用 jquery)

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

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)
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文