Troy Cosentino
Troy Cosentino

Reputation: 4778

Adding parameters to a function that is a parameter

Don't know how to explain this propperly, but basically I have:

mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, function (data) {
    that.tempName(data, "osType", cb);
});

And I want it to look like:

mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, that.tempName.someExtendingFunction("osType", cb));

Where I am looking for "someExtendingFunction" that lets me do this. Is this possible at all? Not a huge deal, but would clean things up.

Thanks

Upvotes: 0

Views: 36

Answers (2)

Bergi
Bergi

Reputation: 664936

There's no native function that does this, but you could write a similar function:

function someExtendingFunction(context, name, type, cb) {
    return function(data) {
        context[name].call(context, data, type, cb);
    };
}

mg.postGiApi("Dashboard",
             "postChartOsTypeData",
             { groupIdList: that.idList },
             someExtendingFunction(that, "tempName", "osType", cb));

Notice that that.tempName.someExtendingFunction(…) will never work, as the that context would be lost. If you call someExtendingFunction as a (Function.prototype) method on the method, you will need to supply the context explicitly, like bind does it.

Upvotes: 1

Jorge Silva
Jorge Silva

Reputation: 4604

For that you can use bind as in Function.prototype.bind:

mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, that.tempName.someExtendingFunction.bind(null, "osType", cb));

This will only work in ECMAScript 5 compatible browsers. If you want something supported by older browsers, you can use underscore.js and use its _.bind function.

mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, _.bind(that.tempName.someExtendingFunction, null, "osType", cb));

This will return a function that will be called with the arguments you pass on to it.

null refers to the this of that variable.

You can read more about bind here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Upvotes: 0

Related Questions