0

I'm bit confused with closure in Javascript.

var updateDom = function(param1, param2, param3) {
    return function(event) {
        // Do something.
    };
};

var updateDomForMyBtn = updateDom(param1, param2, param3);
$btnX.on('click', updateDomForMyBtn);

But why can't I wrap it in an anonymous function, it could be useful if I need to do something more :

var updateDom = function(param1, param2, param3) {
    return function(event) {
        // Do something.
    };
};

var updateDomForMyBtn = updateDom(param1, param2, param3);
$btnX.on('click', function() {
    // Do something more...
    return updateDomForMyBtn
});

What would be the proper way to do it ?

jerome
  • 2,029
  • 4
  • 38
  • 58
  • 2
    What makes you think you can't? – slebetman May 03 '16 at 05:24
  • How do you define "proper"? What are the features of the OP that make it not proper? – RobG May 03 '16 at 05:26
  • Why don't you have look at this question http://stackoverflow.com/questions/111102/how-do-javascript-closures-work. – Ajinkya May 03 '16 at 05:28
  • 1
    In your click handler, you have to actually call `updateDomForMyBtn()` by putting parens after it. `updateDomForMyBtn` is a function reference. So `return updateDomForMyBtn` just returns a function reference from an event handler which does nothing. Presumably you want to execute it with `updateDomForMyBtn()`. – jfriend00 May 03 '16 at 05:33

1 Answers1

1

You actually can wrap it in an anonymous function. You just have to call updateDomForMyBtn at the end of that anon function instead of returning it:

var updateDom = function(param1, param2, param3) {
    return function(event) {
        // Do something.
    };
};

var updateDomForMyBtn = updateDom(param1, param2, param3);
$btnX.on('click', function() {
    // Do something more...
    updateDomForMyBtn();
});
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72