I currently have a working AMD Backbone Model using require.js like so:
// models/game.js
define(['backbone'],
function(Backbone) {
var Game = Backbone.Model.extend({
urlRoot : '/games/'
, defaults : {
name : null
}
});
return Game;
});
The AMD/Backbone organization comes from this tutorial and jrburke's Pull Request for Backbone.
I'd like to use the Backbone Model in Node.js too, because sharing Backbone models and collections has worked well in the past when not using AMD and, well, apparently I'm a masochist.
So I tried the following (inspired by the Backbone mod):
// models/game.js
(function(root, factory) {
if (typeof exports !== 'undefined') {
factory(root, exports, require('backbone'));
}
else if (typeof define === 'function' && define.amd) {
define(['backbone'], function(Backbone, exports) {
factory(root, exports, Backbone);
});
}
}(this, function(root, Game, Backbone) {
Game = Backbone.Model.extend({
urlRoot : '/games/'
, defaults : {
name : null
}
});
return Game;
}));
But Game
is now undefined when I include it in the browser:
// collections/games.js
define(['backbone', 'models/game'],
function(Backbone, Game) {
var Games = Backbone.Collection.extend({
model: Game
, initialize: function() {
console.log(Game)
// Game is undefined
var game = new Game({ name: 'game1' });
}
});
return Games;
});
While I looked at the CommonJS notes, I'm afraid I'm still unclear. How do I use the same Backbone Model file as an AMD file in the browser and as a Node.js module?
And for bonus: Is there a cleaner way than the ~10 lines at the top of each file? Ideally without the define shim.
Have you tried doing it AMD way on node as well?
http://requirejs.org/docs/node.html - might be best solution if you want to have the same AMD modules on both client and backend side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With