0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Not exactly. data is the first parameter, not the last.
You also forgot to pass that as the context. With null it probably won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.