Search code examples
javascriptbackbone.jsscope

Passing the parameters to a callback function : Scope issue


I have this someFunction in the the view of a backbone app. Now I want to send parameters defined in this function to a callback function of jConform function. I cannot figure out how scope works in such cases.

someFunction: function() {
    var thisView = this,
        paramA = 10,
        paramB = $(ev.currentTarget).data("id"),
        paramC = this.getConfig(paramB);

    jConfirm(paramC.jConfirmMessage, "Confirm Deactivation", function (ans) {
                        return thisView.anotherFunction(ans, paramC);
                    });
}


anotherFunction: function(ans, paramC){
    ...
}

How can access the paramC from sumeFunction into anotherFunction ?

Thanks. !


Solution

  • If you are unsure about: if paramC is available in - return thisView.anotherFunction(ans, thisView.paramC).

    Then answer is - Yes, paramC is available in that statement.

    Reason - the callback function defined here remembers the environment in which it was created. This idea is similar to closure. Read about closure and lexical scope here

    But if your question is about how to access paramC inside the body of anotherFunction method, then you can do what as described in the first answer. Or you can create a new property of view object and assign paramC to it.

    And one last thing - javascript has functional scope. you can read about javascript scopes here.

    Hope it helps.