【问题标题】:Share Objectdefinition on Client (Angular) and Server (NodeJs)在客户端 (Angular) 和服务器 (NodeJs) 上共享 Objectdefinition
【发布时间】:2014-06-09 16:46:00
【问题描述】:

我正在尝试在服务器和客户端之间共享特定的 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);
};

目前Foocode 位于单独的文件中。我想我需要更改我的“对象定义”?如果是,如何?我应该把它放在我的项目结构中的什么位置? (我使用this 结构。)

谢谢

【问题讨论】:

  • 您不需要在对象上显式实现toJSON

标签: javascript node.js angularjs mean-stack


【解决方案1】:

将这些类定义放入一个文件中,并使用<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();

更新由于评论中的问题:

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

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;
}

【讨论】:

  • 谢谢。现在我只测试了服务器端的导入,但我偶然发现了一个新的“问题”。根据您的示例,如果我想在“Foo”(单独的文件)中使用“Bar”怎么办?我可以检查“module”或“module.exports”并根据结果添加依赖项,还是有更好的方法?
  • 我会构建一个方法,它会返回所需的类。查看我的更新
  • 再次感谢。现在我也尝试在客户端上使用它,但我在控制台中看到“未捕获的 ReferenceError:模块未定义”。我理解为什么没有在客户端定义“模块”,但我认为“如果(模块)”会优先输出。 '(function (module) { if (module && module.exports) { module.exports = Foo; } }());'这行得通,但这是正确的方法吗?
  • 也许检查typeof module != "undefined"
  • 我检查了“模块!==未定义”,但没有奏效。另一方面,你的确实有效,有点奇怪(至少对我来说)但谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 2021-03-10
  • 1970-01-01
  • 2018-05-13
相关资源
最近更新 更多