I am trying to share a specific javascript "object definition" (class) between server and client. On the server I use Node with Express and on the client Angular. (so far no database, therefore not the entire MEAN stack) The objects will be send via JSON and socket.io.

Example:

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

For now the Foocode is inside a separate file. I guess I need to change my "object definition"? If yes, how? Where do I put it in my project structure? (I use this structure.)

thanks

有帮助吗?

解决方案

Put those class definitions into a file and include into the client with <script> and require with nodejs.

To achieve this on nodejs you need to pass the class def into the module.exports variable, that is only avaiable at nodejs.

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

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

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

Then you can use it in nodejs:

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

This solution works, if you place every class in an own file.

If you want to have all classes in one file:

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

In you nodejs:

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

Update due to the question in the comment:

To use the Foo inside the Bar you need to require this in nodejs and in client you dont need anything (global).

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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top