1
votes

I've got a Backbone model that has some of it's dependencies loaded via require JS. I'm handling it this way to get around the circular dependency issue with Require.js. (We have multiple files requiring models, collections, and views, and some of them are circular.)

The problem is that attributes set on the model (this), are coming out as undefined outside the require statement. Code is here:

define(["jquery", "backbone"],
function($, Backbone) {
    var Model = Backbone.Model.extend({

        initialize: function(options) {
            var that = this;
            require(["collections/agenciesCollection", "collections/usersCollection", "models/userModel"], function(Agencies, Users, User) {
                that.agencies = (!options || !options.agencies) ? new Agencies() : new Agencies(options.agencies);
                that.users = (!options || options.users) ? new Users() : new Users(options.users); 
                if(!options || !options.contact) that.set("contact", new User()); else that.set("contact", new User(options.contact));
                if(!options || !options.admin) that.set("admin", new User()); else that.set("admin", new User(options.contact));
                console.log(that.agencies); // This is set to a collection
            });
            console.log(this.agencies); // This is 'undefined'
            console.log(this); // This has an attribute "agencies" listed in Chrome inspector
        }
  return Model;
});
1

1 Answers

3
votes

You're using the async require call in your constructor so the properties haven't been defined by the time you try to log the values to the console.

These lines:

console.log(this.agencies); // This is 'undefined'
console.log(this); // This has an attribute "agencies" listed in Chrome inspector

are executing before this one:

console.log(that.agencies); // This is set to a collection

UPDATE

Based on your last comment, figured I'd give you an example of how you can simplify your module definition dependency list. You can try requiring your dependencies like this:

define(function (require) {
  var $ = require("jquery");
      backbone = require("backbone");
      agencies = require("collections/agenciesCollection");
      users = require("collections/usersCollection");
      userModel = require("models/userModel");

  // TODO: define your exports using the required dependencies
});

This may also help explain the different ways to load dependencies: https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define