将 javascript 事件监听器附加到变量的理论?

发布于 2024-10-17 12:50:04 字数 401 浏览 8 评论 0原文

我想知道是否有一种方法可以将事件侦听器附加到变量。我们的想法是做这样的事情:

someVar.addEventListener('change', someTodo, false);

所以一旦 someVar 被更改,即 someVar=1,someTodo 将被执行。

我认为要理解的是,理论上,事件监听器可以添加到 DOM 中的所有内容中,问题在于变量不会触发这些事件,而 HTML 对象会触发它们。 如果这确实是正确的,那么扩展的问题将是:如何训练 DOM 对象来触发事件?我读过一些有关原型设计的内容,这就是技巧吗?

请注意:我喜欢自己理解和编写所有代码。所以我宁愿对理论感兴趣,然后使用一些现有的东西,比如 jQuery,其中蕴藏着各种各样的奇迹

。Marco

I was wondering wether there is a way to attach eventlisteners to variables. The idea is to do something like this:

someVar.addEventListener('change', someTodo, false);

So once someVar is changed by i.e. someVar=1, someTodo would be executed.

I think to understand that - in theory - eventlisteners can be added to everything in the DOM, the problem beeing that variables do not trigger those events, while HTML objects DO trigger them.
If that is indeed correct, the extended question would be: How to train DOM objects to trigger events? I have read something about prototyping, is that the trick here?

Please note: I like to understand and write all of my code myself. So I'd rather be interested in the theory then using some existing thing like jQuery, where all sorts of miracles are baked right in.

Marco

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剩余の解释 2024-10-24 12:50:04

安全且经过时间考验的方法是在对象上使用 getter 和 setter(即,只允许通过 getX()/setX() 等对象方法访问变量)。然后您可以重载 setX() 来触发回调。有一些语言,如 Lua 和 Python,可以使用元函数捕获对对象成员的访问,但我不相信 Javascript 以任何方式支持这一点。

The safe and time tested approach is to use getters and setters on your objects (ie, you only allow access to the variable through object methods like getX()/setX()). You could then have overload setX() to trigger callbacks. There are some languages like Lua and Python where access to an object's members can be caught with meta functions but I do not believe Javascript supports this in any way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文