我想为我的客户端早午餐构建和我的节点服务器使用相同的主干模型,节点的模块系统与默认情况下使用的 commonjs 模块几乎相同,但我需要一些思考来设置不同之处.
/server.js
Backbone = require('Backbone');
_ = require('underscore');
var MyAppModel = require('./app/models/MyAppModel');
var app = new MyAppModel();
/app/models/MyAppModel.js
var PeopleCollection = require('../collections/PeopleCollection'); // NODE
var PeopleCollection = require('collections/PeopleCollection'); // BRUNCH
var MyAppModel = Backbone.Model.extend({
initialize: function() {
this.set('people', new PeopleCollection());
}
});
module.exports = MyAppModel;
/app/collections/PeopleCollection.js
var PersonModel = require('../models/PersonModel'); // NODE
var PersonModel = require('models/PersonModel'); // BRUNCH
var PeopleCollection = Backbone.Collection.extend({
model: PersonModel
});
module.exports = PeopleCollection;
/app/models/PersonModel.js
var PersonModel = Backbone.Model.extend({});
module.exports = PersonModel;
基本上唯一阻止我在服务器和客户端上使用相同文件的是需要路径。我可以设置一个全局服务器,然后执行:
if (server)
var PeopleCollection = require('../collections/PeopleCollection');
else
var PeopleCollection = require('collections/PeopleCollection');
我猜应该可行,有没有更优雅的解决方案?