Vigor Vigor - 16 days ago 5
Javascript Question

Call outer function from click event handler in javascript

I was struggled with a javascript question which can be simplified as following:

The real issue is more complicated with Ajax callback and auto list. Based on my real requirement, I do need to call outer function from click event handler. I just want to avoid the handler being called recursively.

JS:

test();

function test() {
$('#btnTest').on('click', function () {
console.log('button clicked');
test();
});
}


HTML:

<button id="btnTest" class="btn btn-danger">Test</button>


The issue here is, when I first click the test button, the message will show once. The second time I clicked the button, it will show twice. The third time I clikced the button, it will show four times! And then 8, 16, etc. I think it's a basic programming logic, but still I don't know how to fix it. I do need to call the outer function from the
OnClick
listener. Any suggestions will be highly appreciated.

Answer

Eventually you can use one function.

test();

function test() {
    $('#btnTest').one('click', function () {
        console.log('button clicked');
        test();
    });
}

Please check it here: fiddle