سؤال

In my jQuery scripts, when the user closes a menu with an animation, I have to call a function after the closing animation is finished. I want to assign this function dynamically by calling a function openStrip() with a parameter. My code looks like:

var FUNCTION_JUST_AFTER_MENU_CLOSE = function(){};
function openStrip(stripId){
      FUNCTION_JUST_AFTER_MENU_CLOSE = function(){
          createStrip(stripId);
      });
}

if I call openStrip("aStripId"), I expect FUNCTION_JUST_AFTER_MENU_CLOSE to be:

// #1    
function(){
    createStrip("aStripId");
}

whereas my current code gives:

//#2
function(){
    createStrip(stripId);
}

i.e, the parameter passed to the function openStrip() is lost while assigning the function() to the variable FUNCTION_JUST_AFTER_MENU_CLOSE.

How can I avoid this.

EDIT: I discovered that my code is actually working. The problem was elsewhere. I got confused because when I looked at Chrome's debugger, it was showing me the function definition as is (#2 in above). But when it actually went down executing that function later in the code, it did evaluate the values of the passed argument, and endedup executing #1.

Thanks for the answer though. I am marking it correct because that is perhaps a better way of assigning the function.

هل كانت مفيدة؟

المحلول

The best way is to return a function, from openStrip like this

function openStrip(stripId) {
    return function() {
        createStrip(stripId);
    };
}

For example,

function openStrip(stripId) {
    return function() {
        console.log(stripId);
    };
}

openStrip("aStripId")();
# aStripId
openStrip("bStripId")();
# bStripId

You can even assign the function objects returned to different variables and use them later on

var aStrip = openStrip("aStripId");
aStrip();
# aStripId
aStrip();
# aStripId
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top