【发布时间】:2020-05-28 20:15:46
【问题描述】:
这是我要开始的。 convert 使用 svgInjector 来启动和销毁资源。
export async function convert(
serializedSvg: string,
svgSourceId: string,
containerId: string
): Promise<string> {
const svgInjector = new SvgInjector(serializedSvg, containerId).inject();
if (!svgInjector.injectedElement) {
throw new Error("Svg not injected");
}
const doc = new TargetDocument({});
const xml = convertRecursively(
svgInjector.injectedElement,
doc,
{
svgSourceId,
}
);
svgInjector.remove();
return doc.saveXML();
}
我怎样才能改写它来让一个更高阶的函数启动、提供和销毁资源svgInjector.injectedElement 给转换函数?
编辑:
这是一个最小的可重现示例:
var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'
function convert(
serializedSvg,
containerId
) {
// make resource available (cross-cutting convern)
var container = document.getElementById(containerId);
var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
container.appendChild(resource);
// core convert functionality does things with resource
console.log(resource.getBBox())
// clean up resource (cross-cutting concern)
resource.remove()
}
convert(svg, "container")
<!DOCTYPE html>
<html>
<head>
<title>Minimal</title>
</head>
<body>
<div id="container">
</div>
</body>
</html>
编辑 2
这是之前编辑中 JavaScript 的 TypeScript 版本
var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'
function convert(
serializedSvg: string,
containerId: string
) {
// make resource available (cross-cutting convern)
var container = document.getElementById(containerId);
if (!(container instanceof HTMLDivElement)) {
throw new Error("Extpected a div element")
}
var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
if (!(resource instanceof SVGSVGElement)) {
throw new Error("Extpected a svg element")
}
container.appendChild(resource);
// core convert functionality does things with resource
console.log(resource.getBBox())
// clean up resource (cross-cutting concern)
resource.remove()
}
convert(svg, "container")
【问题讨论】:
-
您能否将此代码设为适合放入独立 IDE 的 minimal reproducible example?现在
SvgInjector、TargetDocument、convertRecursively,以及任何依赖于它们的东西都没有定义,所以即使开始研究这个,我也需要删除它们或定义它们。下面的答案也是如此。祝你好运! -
@jcalz:感谢您查看我的问题!我添加了一个最小的可重现示例。如果您认为缺少任何内容,请告诉我。
-
如果我将该代码放入The TypeScript Playground,我会遇到几个错误;你是在问那些错误吗?如果没有,你能修复它们吗?
-
@jcalz:见我的第二次编辑。再次感谢你!我不是在问那些错误。我认为错误是因为第一次编辑有 JavaScript 版本。
标签: javascript typescript functional-programming higher-order-functions