user656925
user656925

Reputation:

How do I pass arguments to bound methods? bind vs. anonymous methods

I tried replacing the method name with a method w/ arguments below but this did not work.

// just a minimizer method

function m5(a,b)
  {
  return document.getElementById(a).onkeypress=b;
  }

// On page initialization thse methods are bound to text input boxes

m5('signin_pass',bind_enter_key(event,interface_signin));  // this does not work
m5('upload_file',bind_file_upload);

Upvotes: 0

Views: 127

Answers (3)

jfriend00
jfriend00

Reputation: 707456

You can do it like this with an anonymous function that calls your function with the correct parameters:

// just a minimizer method

function m5(a,b) {
  return document.getElementById(a).onkeypress=b;
}

// On page initialization these methods are bound to text input boxes

m5('signin_pass', function(event) {bind_enter_key(event,interface_signin)});  // this does not work
m5('upload_file', bind_file_upload);

This creates an anonymous function which is passed to m5 as the function and that anonymous function calls your function with the appropriate parameters.

Upvotes: 2

AutoSponge
AutoSponge

Reputation: 1454

m5('signin_pass',bind_enter_key(event,interface_signin));  // this does not work
//first argument is a string, works when passed to getElement..
//second argument is the result of a function call bind_enter_key.
//if the function returns something other than a function, the assignment to a handler will fail

m5('upload_file',bind_file_upload);
//second art is a function, as it should be 

Upvotes: 0

Pavel Podlipensky
Pavel Podlipensky

Reputation: 8269

What does your bind_enter_key function return? It should return a function as you assign it to onkeypress event. If you want to call bind_enter_key function with predefined parameters on keypress event, then you need to build a closure:

m5('signin_pass',function(event){
  bind_enter_key(event,interface_signin);
});

Just a note, I believe bind_enter_key and interface_signin are global and accessible in this point.

Upvotes: 0

Related Questions