Possible Duplicate:
Use of .apply() with 'new' operator. Is this possible?
I have 5 or 6 variable assignments of the form
var analyteSelection = new TemplatedSelectionContainer($('.analyte-container', this), helpers, optionsTemplate);
var instrumentSelection = new AssetBackedSelection($('.instrument-container', this), helpers, optionsTemplate, Assets.instruments, 'Instrument');
var methodSelection = new AssetBackedSelection($('.method-container', this), helpers, optionsTemplate, Assets.methods, 'Method');
As you can see, a significant amount of portion of these constructors are very much alike. It would be nice if I could create a little generic currying builder that would allow me to do something like:
var newSel = selectionContainerBuilder(this, helpers, optionsTemplate)
var analyteSelection = newSel(TemplatedSelectionContainer, '.analyte-container');
var instrumentSelection = newSel(AssetBackedSelection, '.instrument-container', Assets.instruments, 'Instrument');
var methodSelection = newSel(AssetBackedSelection, '.method-container', Assets.methods, 'Method');
I can achieve something similar with
var selectionContainerBuilder = function(ctx, helpers, optionsTemplate) {
return function(FuncDef, selector, a, b, c, d, e, f) {
return new FuncDef($(selector, ctx), helpers, optionsTemplate, a,b,c,d,e,f);
}
}
But seriously ick. I would like to just be able to splice the first three known parameters to the beginning of the arguments array and apply it to the FuncDef but I'm being foiled by the need to use the new operator.
And before someone asks, I can't do new-operator enforcement inside of FuncDef because it's being generated by the coffeescript class keyword.
Of course it can be done. This is the one case where eval
turns out to be useful.
function newApply(cls, args) {
var argsAsString = [];
for (var i = 0, l = args.length; i < l; i++) {
argsAsString.push('args[' + i + ']');
}
return eval('new cls(' + argsAsString.join(',') + ')');
}
(stolen from another thread)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With