4

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

3 Answers 3

6

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();   
}
Sign up to request clarification or add additional context in comments.

Comments

2

A namespace is just an object inside the global scope.

So one alternative is to use with although it has some downsides.

But anyway, check out this sample:

window.test = {
    a: function(){ console.log(this); return 'x'; },
    b: function(){ with (this){ alert(a()); }}        // <- specifying (this)
};

window.test.b();

2 Comments

Using with is not recommended, and is forbidden in ECMAScript 5 strict mode : developer.mozilla.org/en/JavaScript/Reference/Statements/with
@AndrewD. well, I DID warn about some downsides... :P
1

How about passing them as arguments? Something like this:

(function(aM,aV) {
    // use aM and aV internally
})(App.Models,App.Views);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.