首页 > 解决方案 > 如何将事件绑定到 addEventListener('event', callable.bind(???)) 中的可调用对象

问题描述

编辑 1

这个问题几乎立即关闭,因为它应该是重复的。我不敢苟同,因为“原始”问题是关于一般参数绑定的,这个问题(正确地)通过@Phil 的评论解决了一个新问题。我相信在你可能会调用的隐藏参数.bind之前添加参数并不是所有人的常识。为他人着想,我相信这个问题将保持开放。eventevent.preventDefault()

编辑 2

来自@Phil 的另一个知识炸弹(没有讽刺)。在原始问题中显示,使用可以将参数放入的中间匿名函数而不是.addEventListener('event', callable.bind(this, data))一种可能更清晰的方式。.addEventListener('event', e => callable(e, data))这里的一个好处是任何获取的数据(例如从表单中)都是在触发事件时获取的,这显然是有利的。

原始问题

我可能没有正确地做标题,所以请评论一个更合适的标题供我编辑。

最好用一个例子来解释。

这有效:

<script>
form.addEventListener('submit', (e) => {
    e.preventDefault();
    const data = {
        name: form.name.value,
    };
    fetch('logics-url.php', {
            ...,
            body: JSON.stringify(data),
        })
        .then(r => r.json())
        .then(d => console.log(d))
        .catch(e => console.error(e));
});
</script>

然后,当单击外部时,我需要logic-url.php使用不同的(附加)数据进行相同的调用。buttonform

首先,我从内部提取了可调用对象addEventListener,这仍然有效:

<script>
const callable = (e) => {
    e.preventDefault();
    const data = {
        name: form.name.value,
    };
    fetch('logics-url.php', {
            ...,
            body: JSON.stringify(data),
        })
        .then(r => r.json())
        .then(d => console.log(d))
        .catch(e => console.error(e));
}
form.addEventListener('submit', callable);
button.addEventListener('click', callable); // button *is* defined in this scope
</script>

现在我想发送这两个不同addEventListener的数据,这让我失败了。

<script>
const callable = (e, data) => {
    e.preventDefault();
    // Removed data here
    fetch('logics-url.php', {
            ...,
            body: JSON.stringify(data),
        })
        .then(r => r.json())
        .then(d => console.log(d))
        .catch(e => console.error(e));
}

const data1 = {
    name: form.name.value,
};
form.addEventListener('submit', callable.bind(null, data1));

const data2 = {
    name: form.name.value,
    trigger: 1,
};
button.addEventListener('click', callable.bind(this, data2));
</script>

我愚蠢地尝试了 binding e,当它还不存在时,所以我删除了它。然后(如您所见)我尝试绑定null并且this它们都导致错误:

# console
Uncaught ReferenceError: e is not defined at callable

我尝试了不同的变体,但大多数都导致了上述错误。

我也尝试将dataN其作为一个单独的参数传递,结果是:

# console
POST {...}/logics-url.php 400 (Bad Request)
Error: SyntaxError: Unexpected token < in JSON at position 0

必须复制我的代码还是有其他方法?

标签: javascriptbindaddeventlistener

解决方案


推荐阅读