如何在项目中组织JavaScript代码进行可维护性? [英] How to organization JavaScript code in project for maintainability?

查看:123
本文介绍了如何在项目中组织JavaScript代码进行可维护性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主要是一个PHP开发人员,但是最近我一直在玩很多JavaScript,主要是在jQuery中。



问题是代码越来越难调试,这使得更难,因为我的事件监听器散落在HTML之间。



代码处理AJAX调用和DOM操作。

解决方案

分离关注



这意味着你有三种类型的文件,HTML,CSS和JS。



你不会混合任何HTML, CSS或JS。每个人都在自己的文件中。



只要保持一切分离,永远不要使用内联JavaScript或内联CSS,您可以解决大部分代码组织问题。



另一种技术是打包程序和分组。



我的包装商是 browserify (js)和 less (css)



包装商意味着您将许多文件/模块中的所有代码分成良好的设计。然后,因为发送很多小文件是昂贵的,你可以使用一个构建时的打包程序将所有的js转换成一个js文件,并将所有的css转换成一个css文件。



JS本身,我倾向于进一步使用模块加载程序。 Browserify是一个打包程序和一个模块加载程序。



模块加载程序意味着您定义小模块并加载/需要它们,当您需要和需要的地方。



我还实施事件驱动架构和调解员模式,以保持我的代码高度松散耦合。人们可以进一步实施像黑板系统这样的一些东西,但是我没有亲自试过。


Am primarily a PHP developer, but of late I've being playing with alot of JavaScript, mostly in jQuery.

The problem is that the code is getting harder to debug and this made harder because I have event listeners littered across the HTML.

The code handles AJAX calls and DOM manipulation.

解决方案

Separation of concerns

This means you have three types of files, HTML, CSS and JS.

You do not mix any HTML, CSS or JS. Each one of them is in its own file.

Merely by keeping everything seperate and never using inline javascript or inline CSS you can solve most your code organization problems.

Another technique is packagers and minifiers.

My packagers of choice are browserify (js) and less (css)

Packagers mean you have all your code in many files/modules split by good design. Then because sending many small files is expensive you use a build-time packager to turn all your js into one js file and all your css into one css file.

As for JS itself, I tend to go further and use a module loader. Browserify is both a packager and a module loader.

Module loaders mean you define small modules and load/require them when you need to and where you need to.

I also implement event driven architecture and the mediator pattern to keep my code highly loosely coupled. One could go further and implement something like the blackboard system but I havn't tried this personally.

这篇关于如何在项目中组织JavaScript代码进行可维护性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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