Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

addEventListener绑定函数传参完美解决方案?

找了很久没找到
应用场景是这样的

//在请求回调的函数里 省略了请求代码
function callback(data){
    func func_a(){
        //use data do something
    }
    
    document.addEventListener('someone',func_a);
}

大概就是这样的场景
要把data参数传进去大概有
方法1.匿名函数 缺点就是不能remove
方法2.bind 缺点未知,但是看overstack上说也有问题
有没有完美点的方案啊?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你主要在意函数不能被 remove 掉吗?其实这个在 React.hooks 中就有类似的做法:

// 在请求回调的函数里 省略了请求代码
function callback(data){
    function handleSomething(){
        // use data do something
    }
    
    document.addEventListener('click', handleSomething);
    return () => {
        document.removeEventListener('click', handleSomething);
    }
}

const removeEvent = callback({value: 'something...'});

// 当不在需要事件监听器的时候,使用 return 回来的清除函数
removeEvent();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...