2

I have been trying to get namespaces to work with backbone.js for the last hour or so.

I have read: How do I declare a namespace in JavaScript?

And I tried all approaches. Here is the problem:

Backbone.Controller wants to be initialized through a constructur ("new keyword"), because otherwise Backbone.history won't be set. This is the code that I'm trying to put into a namespace, for example "Site.Controllers"

var MainController = Backbone.Controller.extend({

   routes: {
       "help":                 "help",    // #help
   },

   help: function(){}
});

var ws =  new MainController

Whenever I try to put the MainController into some namespace, backbone.js complains that MainController is not a constructor - of course it does, because there doesn't seem to be any way to make a namespace "tree" with constructor functions. If you guys want, I can list all the approaches I tried, but it's exactly the same as from the link provided above. I didn't try putting it into closures, because that is suggested to be very slow.

Community
  • 1
  • 1
Blub
  • 13,014
  • 18
  • 75
  • 102

1 Answers1

1
var namespace = {
    MainController: Backbone.Controller.extend({ ... }),
    HelpController: Backbone.Controller.extend({ ... }),
    ...
};

I'm confused as to what your trying to achieve. An almost fail proof method of creating a namespace is :

var namespace = (function() {
    ...

    return {
        ...
    };

})();

Also yes closures are indeed slower. But I would not worry about this unless your creating the closures millions of times.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • Thank you, I keep making dumb mistakes. I didn't include the external javascript file that had the code, so my namespaces were undefined, then I started fiddling around and I kept getting new errors...oh well. Too used to c# – Blub Apr 11 '11 at 22:26