user656925
user656925

Reputation:

Passing method parameters/arguments to method reference - bind, anonymous, named

I have multiple places in my code where i use method references(i.e. just the method name with no arguments) but I need to pass it specefic arguments.

I don't want to insert an anonymous method b.c. it makes the code unreadable.

I've told I can use the .bind method, but I don't know how to use it properly. Can some one elaborate on how to do this.

Here is one example of where I need to to to this.

How do I use bind to add in parameters to ajax_signin?

if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',ajax_signin,b);}

Upvotes: 0

Views: 128

Answers (2)

jfriend00
jfriend00

Reputation: 707446

If you want ajax_signin() to get called with parameters, then you have to make a separate function that you can pass to ajax that calls ajax_signin() with the appropriate parameters. There are a couple ways to do this:

Using an anonymous function:

if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',function() {ajax_signin("parm1","parm2")},b);}

Creating your own named function:

function mySignIn() {
    ajax_signin("parm1","parm2");
}

if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',mySignIn,b);}

If you want to use .bind() and you are sure you are only running in browsers that support .bind() or you have a shim to make .bind() always work, then you can do something like this:

if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',ajax_signin.bind(this, "parm1","parm2"),b);}

The .bind() call creates a new function that always has a specific this ptr and always has "parm1" and "parm2" as it's first two parameters.

Upvotes: 1

GAgnew
GAgnew

Reputation: 4083

You should be using partial function application! IE: The following:

// This will call a function using a reference with predefined arguments.
function partial(func, context /*, 0..n args */) {
  var args = Array.prototype.slice.call(arguments, 2);
  return function() {
    var allArguments = args.concat(Array.prototype.slice.call(arguments));
    return func.apply(context ? context : this, allArguments);
  };
}

The first argument is the function you want to call, the second argument the context, and any arguments after that will be 'pre-loaded' into the function call.

Note: 'Context' is what this will refer to once the function is being executed.

Upvotes: 0

Related Questions