panthro
panthro

Reputation: 24059

Passing params on promise.done?

I have a promise, and when it's done I wish to run my getContentAll method:

p_numContentTotal.done(getContentAll);

I also wish to pass in a param to that method (the context of the script as I wish to access global vars in the method):

 p_numContentTotal.done(getContentAll(ctx));

But by adding this, the method gets run straight away, how can I get round this?

Upvotes: 0

Views: 58

Answers (2)

shannon
shannon

Reputation: 8784

Usually you'll want your entire script enclosed anyway, to control the namespace. Once you've done so, accomplishing your goal of accessing the current context of your script is already done. This 'javascript closure' is what provides the "anonymous function" capability Artyom mentioned.

How you wrap it is up to you. Simply, your entire script may be an object, a function, a block, or a callback from document ready. Ultimately, this is what allows the magic to happen in other methods anyway.

function main() {
    var ctx = 'current state';
    $("button").click(showContext);
    function showContext() {
        alert(ctx);
    }
}
$(main);

example here: http://jsfiddle.net/s6VDE/1/

note that this preserves reference access (which may or may not be what you want), as demonstrated here: http://jsfiddle.net/s6VDE/5/

Upvotes: 1

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

Wrap it in anonymous function:

p_numContentTotal.done(function () { getContentAll(ctx) });

Or explicitly push ctx as a context of a function and use this to access ctx variable inside it:

function getContentAll() {
   console.log(this); //will print your ctx variable
}
p_numContentTotal.done(getContentAll.bind(ctx));

Upvotes: 1

Related Questions