jQuery 重构/维护

发布于 2024-08-17 07:19:12 字数 732 浏览 14 评论 0原文

我已经搜索了一些,但没有找到任何对我有帮助的问题/答案。问题是我的 jQuery 函数调用变得太大而无法维护。我想知道我是否应该进行更多重构,或者是否有更好的方法来完成所有这些调用。当我进行一次调用时,您会发现作为函数参数的匿名函数最终变得非常大,并使代码的可读性变得非常糟糕。理论上我可以将所有这些分解为各自的功能,但我不知道这是否是最佳实践。下面是到目前为止一些 jQuery 的示例:

$('#dialog').html('A TON OF HTML TO BUILD A FORM').dialog('option', 'buttons', { 'Save': function(){$.post('/use/add/', $('#use_form').serialize(), function(data){ ......There were 4 more lines of this but I'm saving you so you don't rip your eyeballs out hopefully you get the idea.....dialog('option','title','New Use').dialog('open');

正如您所看到的,由于我调用的许多函数都将函数作为参数,所以当我创建匿名函数时,我最终会陷入一片混乱(还有大约 3 个匿名函数)这段代码中的函数声明)

我应该简单地创建一堆函数并调用它们以使其更具可读性吗?我反对这样做的唯一原因是因为我声明了一堆只使用一次的函数。

预先感谢您的帮助!

I've searched a little bit around SO and haven't found any questions/answers that are helping me. The problem is my jQuery function calls are getting much too large to maintain. I'm wondering if I should be refactoring a lot more or if there is a better way to do all of these calls. You'll see as I make one call, the anonymous functions that are arguments for the function end up being very large and make the readability of the code terrible. I could in theory break all these up into their own functions but I don't know if that's a best practice or not. Here is an example of some of the jQuery so far:

$('#dialog').html('A TON OF HTML TO BUILD A FORM').dialog('option', 'buttons', { 'Save': function(){$.post('/use/add/', $('#use_form').serialize(), function(data){ ......There were 4 more lines of this but I'm saving you so you don't rip your eyeballs out hopefully you get the idea.....dialog('option','title','New Use').dialog('open');

As you can see since so many of the functions I'm calling take functions as arguments, when I create anonymous functions I end up with a huge mess (there were about 3 more anonymous function declarations in this code)

Should I simply make a bunch of functions and call those to make it more readable. The only reason I'd be against this is because I'd have a bunch of functions declared that are only used once.

Thanks in advance for the help!

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

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

发布评论

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

评论(6

余生共白头 2024-08-24 07:19:12

在正确的范围内定义函数,这没什么大不了的。

var generateHTML = function() {
  ...
};
var somethingElse = function() {
  ...
};

... some more ...

$('#dialog').html( generateHTML() )...etc

除了一般地重新组织代码(例如,使用面向对象的样式< /a>) 来封装代码,这样代码就不会那么混乱。

Define the functions in the correct scope and it's not a big deal.

var generateHTML = function() {
  ...
};
var somethingElse = function() {
  ...
};

... some more ...

$('#dialog').html( generateHTML() )...etc

There's not much else you can do except reorganize your code in general (say, using an object oriented style) to encapsulate code so it isn't so messy.

可爱暴击 2024-08-24 07:19:12

我反对这个的唯一原因是
因为我有很多功能
声明只使用一次。

正如您当前所做的那样,使用匿名函数与声明正确作用域的命名函数没有什么不同,只不过它们是内联的,并且由于不显示函数名称,因此在许多 JavaScript 调试器中调试起来会稍微困难一些。

如果跨页面的匿名函数有任何模式,我会尝试重构命名函数,为所需的功能提供共同的基础。

我倾向于避免在 jQuery 方法调用中包含大的 html 字符串或嵌入 JavaScript

The only reason I'd be against this is
because I'd have a bunch of functions
declared that are only used once.

Using anonymous functions as you are currently doing is really no different to declaring correctly scoped named functions, except that they are inline and make it slightly more difficult to debug in many JavaScript debuggers as the function name is not displayed.

If there are any patterns to your anonymous functions across pages, I would attempt to refactor named functions out that provide a common base to the functionality needed.

I'd be inclined to avoid having large strings of html within jQuery method calls or embedded inside JavaScript <script> tags and keep these in a separate location that can be easily queried to retrieve the relevant content - this could be text files, etc.

ゝ杯具 2024-08-24 07:19:12

保持可维护性的一个明显方法是使用某种格式。

我理解您不喜欢命名单独使用的函数,但包含名称很容易。模仿作用域的 javascript 习惯用法是将有问题的代码包装在立即调用的匿名函数中:

(function () {
  var f = function (x) ...
  var g = function (y, z) ...
  // operations involving f and g
}()); // called immediately

我更喜欢另一种形式,这使得代码立即执行的事实更加明显:

new function () { // called immediately
  var f = function (x) ...
  var g = function (y, z) ...
  // operations involving f and g
};

还有另一种方式来创建名称:

new function (i, j, k) {
  // functions f and g
  f(i, g(j, k));
}(3, 4, 5);

An obvious way to maintain maintainability is to use some sort of formatting.

I understand your dislike of naming singly used functions, but it's easy to contain the names. The javascript idiom to imitate a scope is to wrap the code in question in an anonymous function that's called immediately:

(function () {
  var f = function (x) ...
  var g = function (y, z) ...
  // operations involving f and g
}()); // called immediately

I prefer another form, which makes the fact that the code is executed right away more visible:

new function () { // called immediately
  var f = function (x) ...
  var g = function (y, z) ...
  // operations involving f and g
};

there's another way to create names with this:

new function (i, j, k) {
  // functions f and g
  f(i, g(j, k));
}(3, 4, 5);
想念有你 2024-08-24 07:19:12

在 jQuery 中很容易陷入永无休止的链接问题。如果适度使用,函数链是很好的,否则需要花很长时间才能阅读和理解 5 分钟前编写的代码。从这个意义上说,按照 slebetman 的建议格式化代码会很有帮助。此外,按照某人或专家的建议来确定您的职能范围也会有很大帮助。

如果您要在重构工作中加倍努力,我建议您考虑某种架构模式(例如 MVC 或 MVP)来组织您的代码。 A List Apart 有一篇关于使用 Javascript 实现 MVC 的精彩文章 。如果视图和模型是分离的,那么很容易让位于使用自定义事件和许多其他易于重用的附加功能。它还迫使人们根据域模型进行思考,而不是 DOM 对象(表、行、div)或事件(单击、按键)等。根据域模型和相关事件(例如 onPostRollback)进行思考>、onPostCreateonCommentAdded 可能适用于例如 SO。 jQuery 最近添加了对绑定自定义事件的支持,这些是一些不错的文章 (第一个第二)解释如何使用。

一般来说,重用视图很困难,但模型在项目中变化很小,是我们可以实现最大可重用性的领域之一。

It's easy to get into the never ending chaining problem in jQuery. Function chaining is good if used moderately, or it takes forever to read and understand code that was written like 5 minutes ago. In that sense, formatting your code as slebetman suggested would be helpful. In addition scoping your functions as suggested by just somebody or thenduks will also be of great help.

If you were to walk an extra mile in your refactoring efforts, I would suggest you consider some sort of architectural patterns such as MVC or MVP to organize your code. A List Apart has a nice article on implementing MVC with Javascript. If there is a separation of view and models, it easily gives way to using custom events and plenty of other additions that are easily reusable. It also forces thinking in terms of the domain model rather than DOM objects (tables, rows, divs) or events (click, keyup), etc. Thinking in terms of the domain model and associated events such as onPostRollback, onPostCreate or onCommentAdded that might be applicable on SO for instance. jQuery recently added support for binding custom events and these are some good articles (first, second) explaining how tos.

In general, its difficult to reuse views, but models change very little across projects and is one area where we can achieve maximum reusability.

滴情不沾 2024-08-24 07:19:12

格式化,格式化,格式化!通过正确使用空格,您的代码CAN看起来可读:

$('#dialog').
    html('A TON OF HTML TO BUILD A FORM').
    dialog('option',
        'buttons', {
            'Save': function(){
                var callback = function(data){
                    // There were 4 more lines of this
                    // but I'm saving you so you don't
                    // rip your eyeballs out hopefully
                    // you get the idea
                }
                $.post(
                    '/use/add/',
                    $('#use_form').serialize(),
                    callback
                )
             }
         }).
    dialog('option',
        'title',
        'New Use').
    dialog('open');

这就是我个人格式化它的方式。还有其他方法,但我强烈建议在行尾保留左大括号/中括号并使用逗号/点/+,因为 javascript 倾向于自动添加“;”如果它认为该行是一个完整的格式良好的语句,则在该行的末尾。

重要的不是你采用什么具体的格式规则。重要的是要保持一致。在某些方面,Python 是对的:有时强迫人们缩进代码是件好事(但我讨厌被 Python 强迫)。

Formatting, formatting, formatting! With proper use of whitespace your code CAN look readable:

$('#dialog').
    html('A TON OF HTML TO BUILD A FORM').
    dialog('option',
        'buttons', {
            'Save': function(){
                var callback = function(data){
                    // There were 4 more lines of this
                    // but I'm saving you so you don't
                    // rip your eyeballs out hopefully
                    // you get the idea
                }
                $.post(
                    '/use/add/',
                    $('#use_form').serialize(),
                    callback
                )
             }
         }).
    dialog('option',
        'title',
        'New Use').
    dialog('open');

This is just how I would personally format it. There are other ways but I'd strongly suggest leaving opening braces/brackets and coutinuing commas/dots/+ at the end of the line because javascript has a tendency to automatically add a ';' at the end of a line if it thinks the line is a complete well-formed statement.

The important thing is not what specific formatting rule you adopt. The important thing is to be consistent about it. In some ways Python was right: it's sometimes good to force people to indent their code (but I hate being forced by Python).

横笛休吹塞上声 2024-08-24 07:19:12

我会尝试尽可能地将代码分解为插件,并且实际上围绕这个原则设计代码。不确定这个想法是否适合您的需求。

I'd try to decompose the code into plugins as much as possible and in fact design the code around this principle. Not sure how well that idea fits your needs.

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