Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Backbone Model with Node.js and AMD (require.js on the browser)

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.

like image 209
baalexander Avatar asked Nov 16 '11 22:11

baalexander


1 Answers

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.

like image 175
Tom Tu Avatar answered Nov 06 '22 05:11

Tom Tu