1

I need to create a new View instance with an arguments array. As I dont want to call

 new View(array)

I tried this solution. But unfortunately this dont work, which means no arg is passed into the initialize function. So is there away to create a new View passing in an array but have the arguments a single once in the initialize function?

Community
  • 1
  • 1
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297

1 Answers1

2

You can achieve this with a bit of prototypal trickery:

function createView() {
    var args = arguments;

    //create a factory function, so we can get the "this" context
    function Factory() { return YourViewClass.apply(this, args);}

    //assign factory prototype (essentially makes factory a YourViewClass)
    Factory.prototype = YourViewClass.prototype;

    //invoke factory function
    return new Factory();
};

var view1 = createView({model:model}, 1, 2, 3);
var view2 = createView.apply(null, argumentArray);

A general solution for instantiating any "class" (constructor function) with variable arguments:

function instantiate(ctor) {
    //strip first arg, pass rest as arguments to constructor
    var args = Array.prototype.slice.call(arguments, 1);
    function Factory() { return ctor.apply(this, args);}
    Factory.prototype = ctor.prototype;
    return new Factory();
};

//call directly
var view1 = instantiate(YourViewClass, {model:model}, 1, 2, 3);

//partially apply to create a factory for a specific view class
var viewFactory = _.partial(instantiate, YourViewClass);
var view2 = viewFactory({model:model}, 1, 2, 3);
jevakallio
  • 35,324
  • 3
  • 105
  • 112