在客户端(Angular)和服务器(NodeJs)上共享Objectdefinition

时间:2014-04-24 11:57:17

标签: javascript node.js angularjs mean-stack

我正在尝试分享特定的javascript"对象定义" (类)服务器和客户端之间。在服务器上,我使用NodeExpress以及客户端Angular。 (到目前为止没有数据库,因此不是整个MEAN堆栈)对象将通过JSONsocket.io发送。

示例:

'use strict';

var Foo = function (fid) {
  this.fid = fid;

  this.toJSON = function () {
    return ('{"fid":"' + this.fid + '"}');
  };

};

Foo.fromJSON = function (json) {
  var obj = JSON.parse(json);
  return new Map(obj.fid);
};

目前,Foo代码位于单独的文件中。我想我需要改变我的对象定义"?如果有,怎么样?我在哪里把它放在我的项目结构中? (我使用this结构。)

感谢

1 个答案:

答案 0 :(得分:2)

将这些类定义放入一个文件中,并将<script>require包含在带有nodejs的客户端中。

要在nodejs上实现此目的,您需要将类def传递给module.exports变量,该变量仅在nodejs中可用。

var Foo = function (fid) {
  this.fid = fid;

  this.toJSON = function () {
    return ('{"fid":"' + this.fid + '"}');
  };    
};

if(module && module.exports)
   module.exports = Foo;

然后你可以在nodejs中使用它:

Foo = require("foo.js");
var foo = new Foo();

如果您将每个班级放在自己的文件中,此解决方案就有效。

如果您想在一个文件所有课程

var Foo = function (fid) {
  this.fid = fid;

  this.toJSON = function () {
    return ('{"fid":"' + this.fid + '"}');
  };    
};

var Bar = function (fid) {
  this.fid = fid;

  this.toJSON = function () {
    return ('{"fid":"' + this.fid + '"}');
  };

};
if(module && module.exports){
   module.exports.Foo = Foo;
   module.exports.Bar = Bar;
}

在你的nodejs:

var Classes = require("classes.js");
var foo = new Classes.Foo();
由于评论中的问题,

更新

要在nodejs和客户端中使用Foo Bar所需的require,你不需要任何东西(全局)。

var Bar = Bar || require("Bar.js");  //if class Bar is undefined, we work on nodejs and need to require the Bar file.

function Foo (){
  var bar = new Bar();
}

if(module && module.exports){
  module.exports.Foo = Foo;
}