gpt4 book ai didi

javascript - Backbone View 不能在 typescript 中使用 Backbone 集合

转载 作者:搜寻专家 更新时间:2023-10-30 21:11:18 26 4
gpt4 key购买 nike

我正在尝试创建一个绑定(bind)到 Backbone 集合的 Backbone View 。但是根据 DefinitelyTyped 中的定义文件Backbone View 对象只能采用模型作为它的泛型类型参数。如何将 View 绑定(bind)到集合?

我当前的代码抛出错误:

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

最佳答案

这个问题的答案基本上是将集合包装在一个单独的模型中,在这种特定情况下,除了无错误地编译外,它几乎没有增加额外的值(value),但实际上我发现存储与集合相关的附加信息很方便,这些信息是还不是集合属性的一部分。

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

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

然后你可以在 View 中使用那个模型

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

关于javascript - Backbone View 不能在 typescript 中使用 Backbone 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23879318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com