Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use namespaces in Backbone with RequireJs

I am unsure how I use namespaces in an modularized (RequireJs) Backbone environment.

I have thought a bit how it could look like but am totally unsure if this is the right way.

app.js (getting executed 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 fully on the wrong way (if yes please correct me!)

like image 349
dev.pus Avatar asked Jul 08 '12 09:07

dev.pus


3 Answers

Have a look at the TODO Backbone + requireJs example:

https://github.com/addyosmani/todomvc

like image 178
CD.. Avatar answered Oct 22 '22 18:10

CD..


Found an real example app using namespaces like mentioned in the start post: https://github.com/nrabinowitz/gapvis

Just have to test it the next days

like image 37
dev.pus Avatar answered Oct 22 '22 18:10

dev.pus


I'm new to backbone, but just read a snippet from the requirejs docs.

A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module. Modules in RequireJS are an extension of the Module Pattern, with the benefit of not needing globals to refer to other modules.

To me, this sounds as if when using requirejs, you can forget all about namespaces, as requirejs takes care of it. You would just have access it differently. When you want to access it from another module, you'd put a path to the file in your array of dependencies, and and feed a respective variable to the following 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.
    }
);

Anyway, perhaps in some cases there is still a need to namespace something, but I think in general, it's worth reading the docs to see if you need to.

like image 25
counterbeing Avatar answered Oct 22 '22 20:10

counterbeing