Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid repeating the namespace in Javascript

I'm working on a backbone application.

I've structured my models + collections + views in different files.

which means a solution like function() { // all my code }() doesn't apply here

I added a namespace e.g App.ModelName App.Views.ViewName etc.

when I'm within the same namespace. How can I avoid repeating it. i.e how can I call ModelName when I'm in a function defined in App.Views.ViewName

at the moment I keep repeating the full string i.e App.XXXX

Thanks

like image 600
hbt Avatar asked Feb 20 '23 21:02

hbt


1 Answers

You have several choices:

1) Create a local variable in each function:

App.ModelName.myFunction = function() {
    var model = App.ModelName;
    // then you can reference just model
    model.myFunction2();
}

2) Create a local variable in each file scope:

(function() {
    var model = App.ModelName;

    model.myFunction = function() {
        // then you can reference just model
        model.myFunction2();
    }


    // other functions here

})();

3) Use the value of this:

App.ModelName.myFunction = function() {
    // call App.ModelName.myFunction2() if myFunction() was called normally
    this.myFunction2();   
}
like image 76
jfriend00 Avatar answered Mar 04 '23 21:03

jfriend00