【发布时间】:2018-02-14 22:01:29
【问题描述】:
我有使用 mootools 进行转换的遗留代码。 Mootools 引入了一个新的带有两个参数的“元素”构造函数。我没有找到任何mootools的类型定义文件,所以我必须自己写。
typescript 标准库 (lib.d.ts) 定义 Element 如下:
var Element: { prototype: Element; new(): Element; };
这使得无法扩展现有接口。
我显然在尝试的是
interface Element {
new(s: string, s2: any): Element;
}
但是,编译器仍然抱怨
var c = new Element('p',{});
作为the contructor expected 0 arguments, but got 2。这里首选的解决方法是什么?
mootools 构造函数
var Element = this.Element = function(tag, props){
var konstructor = Element.Constructors[tag];
if (konstructor) return konstructor(props);
if (typeof tag != 'string') return document.id(tag).set(props);
if (!props) props = {};
if (!(/^[\w-]+$/).test(tag)){
var parsed = Slick.parse(tag).expressions[0][0];
tag = (parsed.tag == '*') ? 'div' : parsed.tag;
if (parsed.id && props.id == null) props.id = parsed.id;
var attributes = parsed.attributes;
if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
attr = attributes[i];
if (props[attr.key] != null) continue;
if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
else if (!attr.value && !attr.operator) props[attr.key] = true;
}
if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
}
return document.newElement(tag, props);
};
// Browser
var Browser = this.Browser = parse(navigator.userAgent, navigator.platform);
if (Browser.Element){
Element.prototype = Browser.Element.prototype;
// IE8 and IE9 require the wrapping.
Element.prototype._fireEvent = (function(fireEvent){
return function(type, event){
return fireEvent.call(this, type, event);
};
})(Element.prototype.fireEvent);
}
【问题讨论】:
-
这是否意味着无法为 mootools 库编写正确的类型定义文件?
-
您需要省略 Dom 的声明并使用一组自定义声明。 mootools 是否真的替换了浏览器中的 element 内置对象?这太可怕了。
-
我把mootools构造函数的定义放在问题里
-
你能指出实际上覆盖
window.Element的 mootools 的 JavaScript 吗? -
它是 Browser.Element,我刚刚添加了它
标签: typescript