4

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.

dertkw
  • 7,798
  • 5
  • 37
  • 45
Nick
  • 5,995
  • 12
  • 54
  • 78
  • possible duplicate of [Javascript Create custom callback](http://stackoverflow.com/questions/2190850/javascript-create-custom-callback) – Manse Apr 13 '12 at 08:37

2 Answers2

12

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);
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • I was neither doubtful nor skeptical :) I just couldn't get it to work straight away because I was passing the function name as a variable (i.e., var a="my_function"; y(a);) rather than passing the function itself. Thanks again. – Nick Apr 13 '12 at 09:43
1

your X object must be a function, not a string.

function X() { /*code*/ }

You can prevent the default action by returning false at the end of X;

function X() { 
  /*code*/ 
  return false;
}

And you can use it inside another function like this:

function Y(callback){
  $('#element').submit(callback);
}
Y(X);
gabitzish
  • 9,535
  • 7
  • 44
  • 65
  • The clarification that I must pass the function itself and not the function name in a string was very useful. Thanks. – Nick Apr 13 '12 at 08:45