jQuery和“组织代码" [英] jQuery and "Organized Code"

查看:77
本文介绍了jQuery和“组织代码"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在努力理解组织jQuery代码的最佳方法.我之前曾问过另一个问题,但我认为我不够具体(这个问题).

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!!

现在这种情况并非不可能.我并不是说这是正确的方法,但是在一个jQuery命令中找到几个级别并开始怀疑在屏幕融化之前还可以添加多少逻辑并不少见.

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.

我的问题是人们如何管理或组织以限制其代码的复杂性?

我在自己的应用程序中列出了操作方式其他帖子 ...

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() { ... });
});

可以优化为:

container.children().unbind().change(function() { ... });

与链接有关,这是简化代码的好方法.

It's all about chaining, a great way to simplify your code.

这篇关于jQuery和“组织代码"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆