开发者

How do I use backbone.js with namespaces?

开发者 https://www.devze.com 2023-02-24 02:44 出处:网络
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?

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 ca开发者_StackOverflown 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号