如何在javascript中添加一个事件监听器,该对象将在对象被操作时触发? [英] how to add an eventListener to an Object in javascript which will fire when object is manipulated?

查看:112
本文介绍了如何在javascript中添加一个事件监听器,该对象将在对象被操作时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的UI结构被动态地操作,并说我有一个 ui_state 对象,我保留用户的最新UI状态,例如哪个选项卡是可见的,什么是



例如:

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

我保留在 html5 localStorage ,当用户刷新网站时,重新打开页面一样。并且每当UI更改此对象相应地更改。而在更改之后,我需要运行,让我们说 updateLocalStorage()这是正常工作。



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



谢谢。

解决方案

您正在将JavaScript编程与DOM编程相结合。事件纯粹是DOM概念。 JS对象不支持事件处理程序。



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


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

For instance:

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

I keep this on html5 localStorage and 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.

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

Thanks.

解决方案

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

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.

这篇关于如何在javascript中添加一个事件监听器,该对象将在对象被操作时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆