javascript - 如何将事件绑定到 addEventListener('event', callable.bind(???)) 中的可调用对象
问题描述
编辑 1
这个问题几乎立即关闭,因为它应该是重复的。我不敢苟同,因为“原始”问题是关于一般参数绑定的,这个问题(正确地)通过@Phil 的评论解决了一个新问题。我相信在你可能会调用的隐藏参数.bind
之前添加参数并不是所有人的常识。为他人着想,我相信这个问题将保持开放。event
event.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
使用不同的(附加)数据进行相同的调用。button
form
首先,我从内部提取了可调用对象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
我必须复制我的代码还是有其他方法?
解决方案
推荐阅读
- javascript - 图标未显示在实现中,但显示在演示中
- c# - 生成应用程序清单任务的配置文件参数的值无效
- android - 如何在按钮单击时动态复制 xaml 代码
- android - 一种方法android的不同行为
- server - 从 Delphi-7 中的客户端调用时,无法在 Windows Server 2012 中执行 asp-classic 脚本
- mysql - SQL - 如何根据另一个最大值选择一个值?
- r - devtools::install() 有效,但 devtools::check() 无效
- algorithm - 读取和写入同一通道的工作池
- node.js - 如何将数据传递给 Express 路由器(并同时更改 url)
- scala - 将简单函数移出 UDF 时任务不可序列化