我正在开发一个使用AngularJS和Socket.io的项目。我发现了this非常好的集成示例。
这是项目结构:
app.js --> app config
bower.json --> for bower
package.json --> for npm
public/ --> all of the files to be used in on the client side
css/ --> css files
app.css --> default stylesheet
img/ --> image files
js/ --> javascript files
app.js --> declare top-level app module
controllers.js --> application controllers
directives.js --> custom angular directives
filters.js --> custom angular filters
services.js --> custom angular services
bower_components/
angular/ --> angular.js
angular-socket-io/ --> socket.io adapter for angular
routes/
index.js --> route for serving HTML pages and partials
socket.js --> serve content over a socket
api.js --> serve JSON to our AngularJS client
views/
index.jade --> main page for app
layout.jade --> doctype, title, head boilerplate
partials/ --> angular view partials (partial jade templates)
partial1.jade
partial2.jade
app.js中的:
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api'),
socket = require('./routes/socket');
...
// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);
// JSON API
app.get('/api/name', api.name);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);
// Socket.io Communication
io.sockets.on('connection', require('./routes/socket'));
现在,虽然通常我只是将服务器逻辑放在app.js
中,但似乎逻辑分为api.js
,socket.js
和index.js
- 我非常喜欢此
但是,让我们说在socket.js
我需要使用api.js
中定义的内容..我应该在var api = require('./api');
中添加socket.js
吗?
答案 0 :(得分:-1)
我最终创建了模块/对象,将所有内容导入app.js并通过引用相互传递(如果需要)..
var mashup = require('./routes/mashupModule'),
socket = require('./routes/socketModule'),
browser = require('./routes/browserModule');
socket.init(server, browser, mashup);
browser.init(socket, mashup);
不确定这是否是在代码中进行某种分离的最佳方式..我习惯使用Java,而且在JS中它通常是一个很大的源文件...