How to use namespaces in Backbone with RequireJs

I'm not sure how to use namespaces in a modular (RequireJs) Backbone environment.

I thought a little how it looks but I'm absolutely not sure if this is correct.

app.js (getting done by main.js)

define('App', ['underscore', 'backbone', 'Router'], function( _, Backbone, Router){
    function initialize(){
        var app = {}; // app is the global namespace variable, every module exists in app

        app.router = new Router(); // router gets registered

        Backbone.history.start();
    }

    return { initialize: initialize }
});

messages.js

define('MessageModel', ['underscore', 'backbone', 'App'], function(_, Backbone, App){
    App.Message.Model; // registering the Message namespace with the Model class

    App.Message.Model = Backbone.Model.extend({
        // the backbone stuff
    });

    return App;
});

Is this the right approach or am I completely mistaken (if so, please correct me!)

+5
source share
3 answers

Check out the TODO Backbone + requireJs example:

https://github.com/addyosmani/todomvc

+5
source

Found a real example application using the namespaces mentioned in the start message: https://github.com/nrabinowitz/gapvis

Just need to check it out on the following days.

+1

, requirejs.

script , , . , , . RequireJS , , .

It sounds to me as if using requirejs you can forget everything about namespaces, since requirejs will take care of that. You will simply have access to it in a different way. When you want to access it from another module, you put the file path in your dependency array and pass the appropriate variable to the next function.

define(["folder/a-script", "folder/another-script"], function(AScript, AnotherScript) {
        // In here the scripts are loaded and can be used, but are called by
        // their relative name in the anonymous function.
    }
);

In any case, perhaps in some cases there is still a need for a namespace, but I think it’s generally worth reading the documents to see if you need to.

+1
source

All Articles