如何使用apply创建新的主干视图

How to create a new Backbone View using apply

本文关键字:视图 何使用 apply 创建      更新时间:2023-09-26

我需要创建一个带有参数数组的新View实例。因为我不想打电话给

 new View(array)

我尝试过这个解决方案。但不幸的是,这不起作用,这意味着没有arg被传递到initialize函数中。那么,是否可以创建一个传入数组的新视图,但在initialize函数中只有一个参数?

你可以通过一点原型技巧来实现这一点:

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);

一个用可变参数实例化任何"类"(构造函数)的通用解决方案:

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);