0

I'm trying to pass a function via a variable to be assigned as part of a click event, for instance:

function bindClick(func) {
    $('#button').click(function() {
        func();
        return false;
    });
}

function configureClick() {
    bindClick(function () { executeClick(message); });
}

function executeClick(message) {
    alert(message);
}

So configureClick() will run at some point, and then #button.click() needs to call the contents of func.

Whatever's happening, is doing so silently, no errors nor desired behavior.

UPDATE: I'm an idiot! The code above is working. My executeClick had a switch-case block which was being ignored as I was passing the incorrect key. Sorry for the trouble D:

8
  • Missing brackets around "bananas!"? Commented Jan 3, 2013 at 11:00
  • 3
    If it doesn't work but there are no errors, make sure you use $(document).ready. Commented Jan 3, 2013 at 11:00
  • sorry, I meant alert('bananas!'), that's just a placeholder for "do other stuff" Commented Jan 3, 2013 at 11:01
  • 1
    Does the element exist? It works just fine as it stands: jsfiddle.net/NJtn9. Commented Jan 3, 2013 at 11:03
  • 1
    Could you perhaps provide a failing demo on jsfiddle.net? Maybe you're calling e.stopImmediatePropagation() or something that prevents the handler from executing. Commented Jan 3, 2013 at 11:14

1 Answer 1

1

You do too much passing of callback function. That' creating lots of closures, which is not needed in such a simple case.

function bindClick(func) {
    $('#button').click(function() {
        func();
        return false;
    });
}


function executeClick(message) {
    alert(message);
}

function configureClick(message){
    bindClick(function(){ executeClick(message) });
}

configureClick('Hello');
Sign up to request clarification or add additional context in comments.

1 Comment

Apologies. I have oversimplied, executeClick() requires a parameter, I'll update my original question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.