Sai
Sai

Reputation: 703

Modifying callback function's argument(s) before calling them

I have a custom object that implements a function that'll be executed later. Here's how someone would call it:

customObject.onSomething(function(e) {
    // do something with e
    console.log('foobar');
});

Here's how onSomething is getting created:

var CustomObject = function() {
    this.onSomething = function(callback) {
        // If the user passes in parameter(s), how can I modify them before calling?
        callback.apply(this);
    }
}

How can I modify the argument(s) the user passed in before performing apply or call on the function?

Upvotes: 1

Views: 3763

Answers (2)

Avish
Avish

Reputation: 4626

apply takes a second parameter which is a list of arguments to pass to the function. call does the same, except it passes its own argument-list (everything after the first parameter which is used as this).

So, if you know which parameters you expect, you can just add them to the invoking function as the second parameter to apply (or as a list of parameters to call):

this.onSomething = function(arg1, arg2) {
   // reverse the first and second arguments
   callback.apply(this, [arg2, arg1]);
   // equivalent:
   callback.call(this, arg2, arg1);
};

If you don't know what kind of arguments to expect, but you still want to do something with them, you can do so with the builtin arguments pseudo-array which holds the arguments given to the current function (even when you don't declare them explicitly).

You can use this to invoke the callback with the same arguments given to the invoking function, or some transformation of them; e.g.:

this.onSomething = function() {
    // call callback with the same arguments we got
    callback.apply(this, arguments);

    // or, make some changes
    var newArgs = ["extra argument", arguments[1], arguments[0]];
    callback.apply(this, newArgs);
};

Upvotes: 8

Kelvin
Kelvin

Reputation: 5307

Sounds like what you're asking for is fairly simple, see below:

var CustomObject = function() {
    this.onSomething = function(callback, param1, param2) {
        param1 += 4;
        param2 = 'Something about ' + param2 + ' is different...';
        callback.apply(this, [param1, param2]);
    }
}

Upvotes: 1

Related Questions