我用的是webpack和TypeScript,看来d3-tip不能和webpack一起工作。我在mouseover events "Uncaught TypeError: Cannot read property 'target' of null"上得到错误。
出现此错误的原因是d3-tip模块中的d3.event为空。
我包含的模块如下:
const d3: any = require("d3");
d3.tip = require("d3-tip");但我猜那里的d3和d3-tip模块中的d3是不同的,这就是问题的根源,但我不知道如何解决它。在d3-tip模块中,我们有:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module with d3 as a dependency.
define(['d3'], factory)
} else if (typeof module === 'object' && module.exports) {
// CommonJS
var d3 = require('d3')
module.exports = factory(d3)
} else {
// Browser global.
root.d3.tip = factory(root.d3)
}
}(this, function (d3) {
...它由webpack编译成
function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// d3.tip
// Copyright (c) 2013 Justin Palmer
//
// Tooltips for d3.js SVG visualizations
(function (root, factory) {
if (true) {
// AMD. Register as an anonymous module with d3 as a dependency.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(465)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
} else if (typeof module === 'object' && module.exports) {
// CommonJS
var d3 = require('d3')
module.exports = factory(d3)
} else {
// Browser global.
root.d3.tip = factory(root.d3)
}
}(this, function (d3) {
...很明显AMD正在使用。如果我能得到d3-tip的工厂,我会解决这个问题。
发布于 2016-09-13 00:28:19
我找到了解决方案。因为我认为,在需要的时候,webpack会生成每个模块的许多实例。我用过single-module-instance-webpack-plugin,它解决了我的问题。
你也只需要在第一时间初始化某个地方的d3,它应该是像vendor.ts这样的文件,其中包括供应商库:
// D3 and third-party components
const d3: any = require("d3");
d3.tip = require("d3-tip");对于纯JS,初始化会很容易。
发布于 2017-03-10 22:52:12
将目标元素作为最后一个参数传递给tip.show()
var tip = require("d3-tip");
var tooltip = tip().html(d => d.value);
vis.call(tooltip)
vis.append("rect")
// ...
.on("mouseover", function() {
tooltip.show.apply(this, [...arguments, this]);
});d3-tip将拾取它并将其用作目标。来自source
if (args[args.length - 1] instanceof SVGElement) target = args.pop()另一种方式:
.on("mouseover", function(d) {
tooltip.show(d, this);
});https://stackoverflow.com/questions/39411091
复制相似问题