如何将JavaScript对象与DOM节点相关联? [英] How to associate javascript objects with DOM nodes?

查看:84
本文介绍了如何将JavaScript对象与DOM节点相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果是,我可以如何将JavaScript对象与DOM节点相关联?我的要求:




  • 真正的对象,而不仅仅是JSON字符串属性等

  • t泄漏记忆

  • 也可以在IE8以上的非标准浏览器中使用



I正在考虑使用一个全局数组来保存数据并将索引放在节点的属性中,但这将会泄漏内存,因为当节点不在DOM中时仍然存在从数组到数据的引用。这是一个Web应用程序,这可能是一个问题。

解决方案

完美的用例为 WeakMap ,假设您定位到较新的浏览器(chrome 36,edge 12,IE 11,firefox 36,safari 7.1):

  let map = new WeakMap(); 
let node = document.getElementById(unicorn);
let data = {};

window.map.set(node,data);

由于WeakMap的键被弱引用,因此不会泄漏。


Can I, and if so, how can I associate javascript objects with DOM nodes? My requirements:

  • real objects, not just JSON-stringified-attributes or so
  • shouldn't leak memory
  • should also work in non-standard browsers like IE8 or so

I was thinking about doing it with a global array that holds the data and putting the indexes in attributes of the nodes, but that would leak memory because there's still a reference from the array to the data when the nodes aren't in th DOM anymore. It's for a web application, so that could be an issue.

解决方案

Perfect use case for the WeakMap, assuming your targeting newer browsers (chrome 36, edge 12, IE 11, firefox 36, safari 7.1):

let map = new WeakMap();
let node = document.getElementById("unicorn");
let data = {};

window.map.set(node, data);

this wont leak since the keys of the WeakMap are weakly referenced.

这篇关于如何将JavaScript对象与DOM节点相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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