Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass function name and then use in event handler

What I want to do is pass the name of a function (X) as an argument into function Y, and then have function Y create an event handler that fires function X.

I want function Y to create the following:

$('#form').submit(function(e){e.preventDefault();X();});

I've tried:

var name="X()";
X(name);

function Y(id){
    $('#element').submit(function(e){e.preventDefault();id;});
}

This, predictably, doesn't work. (I'd didn't really believe it would!) But how can it be done, either (1) by doing it the way I am, or (2) passing the entire X function wholus-bolus into Y?

Thanks.

like image 526
Nick Avatar asked Dec 12 '22 03:12

Nick


1 Answers

here's a demo if you feel doubtful skeptical (sounds better) :D

//create x
function x(){
    alert('im from x');
}

//create y that receives the function
function y(callback){

    //bind your handler which calls callback (which was x)
    $('element').submit(function(){
        callback();
    });
}

//call y that sends over a reference of x
y(x);
like image 51
Joseph Avatar answered Dec 22 '22 07:12

Joseph