【问题标题】:What is the industry and community best practice for coding proper maintainable readable jQuery for a large codebase?为大型代码库编写适当的可维护可读 jQuery 的行业和社区最佳实践是什么?
【发布时间】:2023-03-20 01:10:02
【问题描述】:

来自 Ruby 背景,我习惯于使用带有方法等的类来编写我的所有代码。我确实非常了解 javascript,但我对 jQuery 和它的最佳实践并不陌生。

显然,在 javascript 中模拟类的方法有上百万种。但是,实际 jQuery 社区在现实世界中真正使用的是什么?

具体的例子是理想的。或链接到真实的生产代码。虚构的理想代码的链接也会有所帮助。

谢谢!

【问题讨论】:

  • 很多收藏,但没有回应!
  • 我当然希望这并不意味着 jQuery 被编写为没有可重用类或任何东西的巨大代码块是正常的。我见过的大多数例子都暗示确实如此,但我无法让自己相信。

标签: javascript jquery oop readability


【解决方案1】:

我在当前项目中使用 jQuery 时遇到了同样的问题,我对 jQuery 也有同样的感觉。它就像大的神秘方法链。当它变大时,需要更多时间来理解我之前写的内容。

我发现使 jQuery 代码更易于维护的唯一方法是 Module Pattern。也许它会很有用。你也可以看看 Ajaxian jQuery vs. Prototype: OO JavaScript with or without training wheels 关于同样问题的文章。

【讨论】:

    【解决方案2】:

    这不适用于 jQuery,但我喜欢在我自己的代码中模拟类的对象字面量语法。

    http://ajaxian.com/archives/show-love-to-the-object-literal

    我倾向于经常使用类似这样的(简化的)框架:

    var Widget = {
    
        sound:'bleep',
    
        load:function(){
    
            // do stuff here that doesn't need to wait until the DOM is ready.
    
            // Inside an anonymous function (such as the 'click' handler below),
            // 'this' loses its scope and no longer refers to the widget object.
            // To retain a reference to the widget object, assign 'this' to a
            // variable. I use an underscore... some people like 'self':
            var _ = this;
    
            // when the DOM is ready, run the init "method":
            $(document).ready(function(){
                _.init(); // the underscore now refers to the widget object
            });
    
        },
    
        init:function(){
    
            var _ = this;
    
            // whenever a <p class="noisy"> element is clicked, call makeNoise()
            $("p.noisy").click(function(){
                _.makeNoise();
            });
    
        },
    
        makeNoise:function(){
    
            alert(this.sound); // alert 'bleep'
    
        }
    
    };
    
    Widget.load();
    

    编辑:有关使用“this”关键字的更多信息,如上所述:

    http://groups.google.com/group/jquery-en/browse_thread/thread/328d07f90467cccc?pli=1

    【讨论】:

    • 这确实很好读。这是一个常见的 jQuery 习语吗?
    • 我在老 jQuery 圈子里看到了很多,是的。虽然我相信一般结构可以与其他库同样好用。由于 jQuery 非常依赖匿名函数,因此您需要注意“this”关键字。我在原帖中添加了一个链接。
    • 对象字面量语法的一大缺点是您不能创建多个实例。如果我想在屏幕上有两个 Widget 实例怎么办?我建议您使用简单容器并使用 jQuery 实例的真实对象。函数小部件(){};小部件.prototype.load() {};等
    【解决方案3】:

    我会从这里开始寻找灵感:

    http://errtheblog.com/posts/73-the-jskinny-on-jquery

    【讨论】:

    • 这是我不想要的完美示例。这篇文章展示了如何做非常基础的 jQuery。我想知道人们使用什么来上课和管理大型代码库。
    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多