简体   繁体   中英

How do I use backbone.js with namespaces?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM