骨干视图不能在打字稿中使用Backbone集合

时间:2014-05-27 00:21:39

标签: javascript backbone.js typescript

我试图创建一个绑定到Backbone集合的Backbone视图。但是根据DefinitelyTyped的定义文件,Backbone视图对象只能将模型作为它的泛型类型参数。如何将视图绑定到集合?

我当前的代码抛出错误:

export class EnvironmentMenu extends Backbone.View<EnvironmentCollection>{

constructor(options?: Backbone.ViewOptions<EnvironmentCollection>) {
         super(options);
    }
}

错误为Type 'EnvironmentCollection' does not satisfy the constraint 'Backbone.Model' for type parameter 'TModel extends Backbone.Model'

我假设是因为定义中的这一行:

class Collection<TModel extends Model> extends ModelBase

我的模特和收藏品目前只是贝壳

环境模型

export class EnvironmentModel extends Backbone.Model {
    constructor(options?) {
        super(options);
    }
}

环境集合

export class EnvironmentCollection 
    extends Backbone.Collection<EnvironmentModel> {

    constructor(options?) {
        super(options);
        this.model = EnvironmentModel;
    }
} 

1 个答案:

答案 0 :(得分:2)

答案是基本上将集合包装在一个单独的模型中,在这个特定的场景中除了编译没有错误之外几乎没有额外的价值,但我实际上发现它可以方便地存储与集合相关的其他信息。尚未成为集合属性的一部分。

export class EnvironmentViewCollection extends Backbone.Model {
    constructor(collection: EnvironmentCollection, options?: any) {    
         options = options || {};
         options.innerCollection = collection;
    }

    getCollection() : EnvironmentCollection {
         return this.get('innerCollection');
    }
}

然后您可以在视图中使用该模型

export class EnvironmentMenu extends Backbone.View<EnvironmentViewCollection> {
    constructor(options?: Backbone.ViewOptions<EnvironmentViewCollection>) {
        super(options);
    }

    useCollection() : void {
        var collectionLength = this.model.getCollection();
        console.log('The length of the collection is', collectionLength);
    }
}