首页 > 其他 > 详细

d3.select(this)不能用箭头函数

时间:2018-11-10 11:12:15      阅读:131      评论:0      收藏:0      [点我收藏+]

d3中典型的数据绑定片段

    const items = svg.selectAll(‘g‘)
                    .data(gdfs,(d)=> d.name);

    const enter = items.enter().append(‘g‘);
    //console.log(enter);
    //没有update()函数了,添加删除后,全部更新
    enter.merge(items)
        .attr(‘class‘,(d)=> d.name)
        .each(function(d) {
            const g = d3.select(this);
            console.log(‘g‘,g);
            //do some with g;
        });

    items.exit().remove();
}

对g元素如果需要进一步绑定数据进行操作,则调用each 传入匿名函数。 里面使用d3.select(this) ,这个d3 选择集,指向each对应的dom元素。

在这里,要注意this的问题。如果使用es6的箭头函数() =>{} ,会报错,必须使用传统的funcion(d){}

区别在这里,箭头函数不绑定this  https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

 

不绑定this

在箭头函数出现之前,每个新定义的函数都有它自己的 this

箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this

 

但是d3这里,显然是依赖局部的this的,用箭头函数,是找上一层的this,会报错。

 

 

——总之,用d3.select(this)的地方,就用传统的function就好了。反正也不是很多。

 

d3.select(this)不能用箭头函数

原文:https://www.cnblogs.com/xuanmanstein/p/9938379.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!