1

I'm using Durandal, and I'm trying to use this module as a dependency for another module:

define('Beer', function () {
    return function Beer (name, brewery) {
        this.name = name;
        this.brewery = brewery;
    };
});

In the other module, I do this:

define(['knockout', 'models/Beer'], function (ko, Beer) {
    return {
        displayName: 'Add',
        name: ko.observable(),
        brewery: ko.observable(),
        save: function () {
            var beer = new Beer(this.name(), this.brewery());
            console.log(beer);
        }
    }
});

My javascript is loaded, because I define it in my paths (and I checked in Firebug). But the Beer argument in my second module is undefined. I don't know why, as my Beer module does return something (it returns the function). What else can I look at? Most solutions I find are that the (first) module isn't returning anything, but mine clearly is.

UPDATE Apparently, when I remove the name of my Beer module, it works:

define(function() {
    return function Beer (name, brewery) {
        // ...
    }
});

Even though this code would seem to work, it doesn't for me. Can anyone tell me why?

Community
  • 1
  • 1
Peter
  • 13,733
  • 11
  • 75
  • 122

1 Answers1

3

You are mixing named modules with anonymous modules in your approach.

If you name the module 'Beer', you require it using the name, not the path:

require(['Beer'], function (Beer) {
    var a = new Beer();
});

If you remove the name from the Beer module, you have an anonymous module which you can load by path:

require(['path/to/Beer'], function (Beer) {
    var a = new Beer();
}

Edit: the topic you linked to does not use RequireJS, even though it looks similar.

Hans Roerdinkholder
  • 3,000
  • 1
  • 20
  • 30