随着像jQuery这样的JavaScript框架使客户端web应用程序更丰富,功能更强大,我开始注意到一个问题…

你到底是怎么组织起来的?

把所有的处理程序放在一个地方,并为所有事件编写函数? 创建函数/类来包装您的所有功能? 疯狂地写作,只希望结果是最好的? 放弃,找一份新工作?

我提到了jQuery,但它实际上是一般的JavaScript代码。我发现,当一行一行开始堆积时,管理脚本文件或找到您要找的内容变得越来越困难。我发现的最大问题可能是,做同一件事有太多的方法,很难知道哪一种是目前普遍接受的最佳实践。

有什么通用的建议可以让你的.js文件像你的应用程序的其他部分一样漂亮整洁吗?或者这只是IDE的问题?还有更好的选择吗?


EDIT

这个问题主要是关于代码组织,而不是文件组织。有一些合并文件或拆分内容的好例子。

我的问题是:目前普遍接受的组织实际代码的最佳实践方式是什么?您的方法是什么,甚至推荐的方法是什么,以与页面元素交互并创建互不冲突的可重用代码?

有些人列出了名称空间,这是个好主意。还有什么其他方法,更具体地说,处理页面上的元素并保持代码的组织和整洁?


当前回答

"Write like crazy and just hope it works out for the best?", I've seen a project like this which was developed and maintained by just 2 developers, a huge application with lots of javascript code. On top of that there were different shortcuts for every possible jquery function you can think of. I suggested they organize the code as plugins, as that is the jquery equivalent of class, module, namespace... and the whole universe. But things got much worse, now they started writing plugins replacing every combination of 3 lines of code used in the project. Personaly I think jQuery is the devil and it shouldn't be used on projects with lots of javascript because it encourages you to be lazy and not think of organizing code in any way. I'd rather read 100 lines of javascript than one line with 40 chained jQuery functions (I'm not kidding). Contrary to popular belief it's very easy to organize javascript code in equivalents to namespaces and classes. That's what YUI and Dojo do. You can easily roll your own if you like. I find YUI's approach much better and efficient. But you usualy need a nice editor with support for snippets to compensate for YUI naming conventions if you want to write anything useful.

其他回答

我为所有我真的不需要在屏幕上实例化几次的东西创建单例,为其他所有东西创建一个类。所有这些都放在同一个文件的同一个名称空间中。所有的东西都是用UML、状态图进行注释和设计的。javascript代码是清楚的html,所以没有内联javascript,我倾向于使用jquery来最小化跨浏览器的问题。

您没有提到服务器端语言是什么。或者,更确切地说,您在服务器端使用什么框架(如果有的话)。

IME,我在服务器端组织东西,让它全部震动到网页上。该框架的任务不仅是组织每个页面必须加载的JS,还包括与生成的标记一起工作的JS片段。这样的片段通常不希望发出超过一次——这就是为什么它们被抽象到框架中,以便代码处理该问题。: -)

对于必须发出自己的JS的最终页面,我通常发现生成的标记中有一个逻辑结构。这种本地化的JS通常可以在这种结构的开始和/或结束处组装。

请注意,这些都不能免除您编写高效JavaScript的责任!: -)

你可以使用jquery mx(在javascriptMVC中使用),这是一组允许你使用模型、视图和控制器的脚本。我曾在一个项目中使用它,并帮助我创建结构化javascript,由于压缩,脚本大小最小。以控制器为例:

$.Controller.extend('Todos',{
  ".todo mouseover" : function( el, ev ) {
   el.css("backgroundColor","red")
  },
  ".todo mouseout" : function( el, ev ) {
   el.css("backgroundColor","")
  },
  ".create click" : function() {
   this.find("ol").append("<li class='todo'>New Todo</li>"); 
  }
})

new Todos($('#todos'));

如果对视图和模型部分不感兴趣,也可以只使用querymx的控制器端。

我用这个小东西。它为JS和HTML模板提供了“include”指令。它完全消除了混乱。

https://github.com/gaperton/include.js/

$.include({
    html: "my_template.html" // include template from file...
})
.define( function( _ ){ // define module...
    _.exports = function widget( $this, a_data, a_events ){ // exporting function...
        _.html.renderTo( $this, a_data ); // which expands template inside of $this.

        $this.find( "#ok").click( a_events.on_click ); // throw event up to the caller...
        $this.find( "#refresh").click( function(){
            widget( $this, a_data, a_events ); // ...and update ourself. Yep, in that easy way.
        });
    }
});

在我的上一个项目- viajeros.com -我使用了几种技术的组合。我不知道如何组织一个网页应用程序——Viajeros是一个面向旅行者的社交网站,它有明确定义的部分,所以很容易将每个部分的代码分开。

我根据站点部分使用名称空间模拟和延迟加载模块。在每个页面加载我声明一个“vjr”对象,并总是加载一组常用函数到它(vjr.base.js)。然后每个HTML页面用简单的语句决定哪些模块需要:

vjr.Required = ["vjr.gallery", "vjr.comments", "vjr.favorites"];

Vjr.base.js从服务器获取并执行每一个gzip文件。

vjr.include(vjr.Required);
vjr.include = function(moduleList) {
  if (!moduleList) return false;
  for (var i = 0; i < moduleList.length; i++) {
    if (moduleList[i]) {
      $.ajax({
        type: "GET", url: vjr.module2fileName(moduleList[i]), dataType: "script"
      });
    }
  }
};

每个“模块”都有这样的结构:

vjr.comments = {}

vjr.comments.submitComment = function() { // do stuff }
vjr.comments.validateComment = function() { // do stuff }

// Handlers
vjr.comments.setUpUI = function() {
    // Assign handlers to screen elements
}

vjr.comments.init = function () {
  // initialize stuff
    vjr.comments.setUpUI();
}

$(document).ready(vjr.comments.init);

鉴于我有限的Javascript知识,我知道一定有更好的方法来管理这个,但到目前为止,它为我们工作得很好。