javascript - 如何在javascript中向对象添加事件监听器,当对象被操作时会触发?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3903226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:37:33  来源:igfitidea点击:

how to add an eventListener to an Object in javascript which will fire when object is manipulated?

javascripteventsjavascript-eventsevent-handling

提问by KakambaWeb

I have a complicated UI structure which is manipulated dynamically, and say I have an ui_stateobject where i keep user's latest UI states such as which tab was visible, what was inside that tab etc.

我有一个复杂的 UI 结构,它是动态操作的,并且说我有一个ui_state对象,我可以在其中保留用户的最新 UI 状态,例如哪个选项卡可见,该选项卡里面有什么等等。

For instance:

例如:

var ui_states = {
  tabs : [
    {
      name     : "some tab",
      active   : true,
      children : { ... }
    },
    {
      name     : "some other tab",
      children : { ... }
    }
  ]
}

I keep this on html5 localStorageand when user refreshes the site it reopens the page the same. And everytime when the UI changes this object is changed accordingly. And just after changing it i need to run let's say updateLocalStorage()which is working perfectly.

我保持这个状态html5 localStorage,当用户刷新网站时,它会重新打开页面。每次 UI 更改时,此对象都会相应更改。在更改它之后,我需要运行让我们说updateLocalStorage()哪个工作正常。

My question is for this flow, can i create a custom event to my ui_statesobject something like ui_states.addEventListener('onchange', function(){ // do stuff })to not to run that updateLocalStorage()function every time when i manipulate the object?

我的问题是对于这个流程,我可以为我的ui_states对象创建一个自定义事件,例如每次操作对象时都ui_states.addEventListener('onchange', function(){ // do stuff })不要运行该updateLocalStorage()函数吗?

Thanks.

谢谢。

回答by staticsan

You're mixing up JavaScript programming with DOM programming. Events are purely a DOM concept. JS objects do not support event handlers.

您将 JavaScript 编程与 DOM 编程混为一谈。事件纯粹是一个 DOM 概念。JS 对象不支持事件处理程序。

The only way to do it is to create getters and setters. There are ways to do this with special properties, but unfortunately, browser support is a bit maybe. The other way to do it is using explicit methods and private variables. This is possible but a little complex.

唯一的方法是创建 getter 和 setter。有一些方法可以使用特殊属性来做到这一点,但不幸的是,浏览器支持可能有点。另一种方法是使用显式方法和私有变量。这是可能的,但有点复杂。