Alex Rivera | Logout

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

Asked 2011-11-16T22:48:28.877
9

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 Backb

Edit
Report

1 Answer

4

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.

answered 2011-11-24T21:13:16.047

Your Answer