我正在使用 TypeScript,我有几个 functional mixins 、Eventable
和 Settable
,我想将其混合到 Model
类中(假装它类似于 Backbone.js 模型):
function asSettable() {
this.get = function(key: string) {
return this[key];
};
this.set = function(key: string, value) {
this[key] = value;
return this;
};
}
function asEventable() {
this.on = function(name: string, callback) {
this._events = this._events || {};
this._events[name] = callback;
};
this.trigger = function(name: string) {
this._events[name].call(this);
}
}
class Model {
constructor (properties = {}) {
};
}
asSettable.call(Model.prototype);
asEventable.call(Model.prototype);
上面的代码工作正常,但如果我尝试使用其中一种混合方法,如 (new Model()).set('foo', 'bar')
,则无法编译.
我可以解决这个问题
- 为 mixins 添加
interface
声明 - 在
Model
中声明虚拟get
/set
/on
/trigger
方法> 声明
是否有绕过虚拟声明的干净方法?
最佳答案
这是使用 interfaces
处理混入的一种方法和一个 static create()
方法。接口(interface)支持多重继承,因此您不必重新定义 interfaces
为你的 mixins 和 static create()
方法负责返回一个 Model()
的实例。作为IModel
(需要 <any>
转换才能抑制编译器警告。)您需要复制 Model
的所有成员定义。在 IModel
这很糟糕,但它似乎是在当前版本的 TypeScript 中实现你想要的最干净的方法。
编辑:我已经确定了一种稍微简单的方法来支持混入,甚至创建了一个辅助类来定义它们。详情可查over here .
function asSettable() {
this.get = function(key: string) {
return this[key];
};
this.set = function(key: string, value) {
this[key] = value;
return this;
};
}
function asEventable() {
this.on = function(name: string, callback) {
this._events = this._events || {};
this._events[name] = callback;
};
this.trigger = function(name: string) {
this._events[name].call(this);
}
}
class Model {
constructor (properties = {}) {
};
static create(): IModel {
return <any>new Model();
}
}
asSettable.call(Model.prototype);
asEventable.call(Model.prototype);
interface ISettable {
get(key: string);
set(key: string, value);
}
interface IEvents {
on(name: string, callback);
trigger(name: string);
}
interface IModel extends ISettable, IEvents {
}
var x = Model.create();
x.set('foo', 'bar');
关于TypeScript 中的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719844/