繁体   English   中英

为大型代码库编写适当的可维护可读jQuery的行业和社区最佳实践是什么?

[英]What is the industry and community best practice for coding proper maintainable readable jQuery for a large codebase?

来自Ruby背景,我习惯用类和方法等编写所有代码。 我非常了解javascript,但我是jQuery及其最佳实践的新手。

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

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

谢谢!

这不适用于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

我从这里开始寻找灵感:

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

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

我发现制作更易维护的jQuery代码的唯一方法是模块模式 。也许它可以是有用的。你也可以看看Ajaxian jQuery vs. Prototype:OO JavaScript有或没有训练轮关于同样问题的文章。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM