0

Scenario 1:

$(function () {
    $('#disp_body').on('change', '#image', showMyImage(this));
});

If I call the function showMyImage directly it calls on page load itself.

Scenario 2:

But if I call through closure function. The event properly listened and handled. So it's working properly.

$(function () {
    $('#disp_body').on('change', '#image', function() {
        showMyImage(this);
    });
});

I like to know really why the scenario 1 is not working but scenario 2.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gvgvgvijayan
  • 1,851
  • 18
  • 34
  • There are two levels of execution here. You should debug the execution order to understand why this is happening otherwise you'll be running into this frequently. – Dylan Wright Dec 27 '17 at 13:17

1 Answers1

1

This answer is relevant: https://stackoverflow.com/a/7102440/7316502

In case 1, you are invoking a function, and passing its return value to the change listener as a callback. This results in the premature execution of showMyImage.

In case two, you are passing a function to be used as a callback, but you are not calling it directly. This allows the change listener to call it and invoke showMyImage on the change event as you desire.

thmsdnnr
  • 1,282
  • 10
  • 17