Question

I'd like to use the very same Backbone Models for my clientside brunch build and my node server, node's module system is pretty much the same as the commonjs modules burnch uses by default, but I need a bit of thinkering to set up what's different.

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

basically the only thing that prevents me from using the same file on server and client is that require path. I could set a server global and then do:

if (server)
    var PeopleCollection = require('../collections/PeopleCollection');
else
    var PeopleCollection = require('collections/PeopleCollection');

should work I guess, are there more elegant solutions to this?

Was it helpful?

Solution

There is no need to use absolute paths. Brunch supports relative paths. You can just use:

var PeopleCollection = require('../collections/PeopleCollection');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top