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

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

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

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

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


EDIT

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

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

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


当前回答

你可以使用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的控制器端。

其他回答

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

对于JavaScript组织一直使用以下

Folder for all your javascript Page level javascript gets its' own file with the same name of the page. ProductDetail.aspx would be ProductDetail.js Inside the javascript folder for library files I have a lib folder Put related library functions in a lib folder that you want to use throughout your application. Ajax is the only javascript that I move outside of the javascript folder and gets it's own folder. Then I add two sub folders client and server Client folder gets all the .js files while server folder gets all the server side files.

Dojo从一开始就使用模块系统。事实上,它被认为是Dojo的基石,是将所有Dojo结合在一起的粘合剂:

dojo。要求——官方文件。 理解dojo.declare, dojo。Require和dojo. provider。 引入Dojo。

使用模块Dojo可以实现以下目标:

Namespaces for Dojo code and custom code (dojo.declare()) — do not pollute the global space, coexist with other libraries, and user's non-Dojo-aware code. Loading modules synchronously or asynchronously by name (dojo.require()). Custom builds by analyzing module dependencies to create a single file or a group of interdependent files (so-called layers) to include only what your web application needs. Custom builds can include Dojo modules and customer-supplied modules as well. Transparent CDN-based access to Dojo and user's code. Both AOL and Google carry Dojo in this fashion, but some customers do that for their custom web applications as well.

按需加载所需的代码。谷歌对他们的Google .loader做了类似的事情

看看JavasciptMVC吧。

你可以:

将代码分成模型层、视图层和控制器层。 将所有代码压缩到一个生产文件中 自动生成代码 创建并运行单元测试 还有更多……

最重要的是,它使用jQuery,所以你也可以利用其他jQuery插件。